std :: map <tstring <std :: map <tstring,unsigned int >>赋值失败

ast*_*ght 1 c++ stl

基本上我有(州,州代码)对,这是国家[美国] - > [VT] - > 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
}
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*sop 6

std :: map上的operator []是非const的,因为它创建了条目(如果它尚不存在).所以你不能以这种方式使用const_iterator.您可以在const映射上使用find(),但仍然不允许您修改它们的值.

而Smashery是对的,考虑到你有一张地图,你会以一种奇怪的方式进行第一次查找.既然你明确地修改了这个东西,那么这有什么问题呢?

countryList[_T("USA")][_T("MN")] = 5;
Run Code Online (Sandbox Code Playgroud)