Sunday, May 1, 2011

std::map<tstring<std::map<tstring, unsigned int>> assignment fail

basically i have (state, state code) pairs, that are subsets of country [USA] -> [VT] -> 32

so i'm using std::map<tstring<std::map<tstring, unsigned int>> but i'm having trouble with assignment of the state code

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>'

Thanks in advance!.

From stackoverflow
  • If you're wanting to find an element in a map, you can use the find method:

    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;
    }
    

    Also, you'll want to be using iterator, and not const_iterator. You can't modify the map if you use a const_iterator, because: it's const!

  • operator[] on std::map is non-const, because it creates the entry if it doesn't already exist. So you can't use a const_iterator in this way. You can use find() on const maps, but that still won't let you modify their values.

    And Smashery is right, you're doing the first lookup in a strange way considering that you have a map. Since you're clearly modifying the thing, what's wrong with this?

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

0 comments:

Post a Comment