2009-04-23 13 views
1

基本的に私は国のサブセットである(州、州コード)のペアを持っています [米国] - > [VT]std :: map <tstring <std :: map <tstring、unsigned int >>割り当てが失敗しました

32はので、私はstd::map<tstring<std::map<tstring, unsigned int>>を使用していますが、私は状態コードの割り当てとのトラブルを抱えている

for(std::map<tstring, std::map<tstring, unsigned int>>::const_iterator it = countrylist.begin(); it != countrylist.end(); ++it) 
{ 
foundCountry = !it->first.compare(_T("USA")); //find USA 
if(foundCountry) it->second[_T("MN")] = 5; //Assignment fails 
} 

error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>'

+0

以前にSTLを使用しましたか? – user44511

+0

あまりあまり明らかにそうではないので私は尋ねている。私はアマゾンから来たSTLの本を持っています。 – 0x4f3759df

答えて

6

std :: mapのoperator []は、エントリが存在しない場合は作成されるため、非constです。したがって、このようにconst_iteratorを使用することはできません。 constマップでfind()を使うことはできますが、それでも値を変更することはできません。

Smashheryが正しいとすれば、あなたはマップを持っていると考えると奇妙な方法で最初の検索をしています。あなたは明らかに物を修正しているので、これは何が問題なのですか?

countryList[_T("USA")][_T("MN")] = 5; 
3

あなたがマップ内の要素を検索したい場合は、することができますfindメソッドを使用してください:

std::map<tstring, std::map<tstring, unsigned int>::iterator itFind; 
itFind = countrylist.find(_T("USA")); 
if (itFind != countrylist.end()) 
{ 
    // Do what you want with the item you found 
    it->second[_T("MN")] = 5; 
} 

また、const_iteratorではなく、イテレータを使用したいと思うでしょう。 const_iteratorを使用している場合、マップを変更することはできません。これはconstです:

関連する問題