2009-04-23 44 views
1

基本上我有(狀態,狀態碼)對,它們是國家 [USA] - > [VT] - > 32std :: map <tstring <std :: map <tstring,unsigned int >>賦值失敗

所以我用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 2009-04-23 22:50:23

回答

6

std :: map上的operator []是非const的,因爲如果條目尚不存在,它會創建該條目。所以你不能以這種方式使用const_iterator。你可以在const地圖上使用find(),但仍然不會讓你修改它們的值。

Smashery是對的,你正在以一種奇怪的方式進行第一次查找,因爲你有一張地圖。既然你明確地修改了這個東西,那麼這有什麼問題呢?

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

如果你想在地圖中找到一個元素,你可以使用查找方法:

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,則無法修改地圖,因爲:它是常量!

相關問題