简体   繁体   中英

How can I check values in a C++ map without getting compiler errors in a “const” member function?

I have a member function that compares data in a C++ map. I declared the member function as constant:

bool operator == (UnitSet otherSet) const;

but as soon as I use myMap["l"] to access and compare values I get compiler errors about myMap being constant. Is there a way around this while keeping the const directive?

I know an empty value is created for the "l" key if it didn't exist when I check it, but that won't change the value / behaviour of my UnitSet - maybe I'm trying to be too picky here though and should just drop the "const". What is the good way to go about this?

Thanks.

Firstly, you should change your function signature to accept otherSet by const reference, as you have no need to copy it and won't be modifying it:

bool operator==(const UnitSet& otherSet) const;

Then, rather than using the non- const operator[] , use find() or begin() / !=end() / ++ to get const_iterator s into your map s for the comparison. As find() , begin() and operations on const_iterator only require const access to map , they can be used from your const member function.

map<X, Y>::const_iterator i = the_map.find(key);
if (i != the_map.end())
    // here, i->first is the key, i->second is the value
else
    // key wasn't in the map after all...

std::map unfortunately doesn't have a const overload of the [] operator. This is because whenever you access a key that doesn't exist, the map creates an element for it; if the map was const , that would be impossible. Therefore, there's no way to call it with a constant map. It isn't related to the behavior of your UnitSet class.

You'll have to use myMap.find(TKey) to get an iterator to your element, which returns myMap.end() if it can't find it.

Map iterators point to a std::pair of your key and value, so you need to access the second member of it to get your value ( first being the key).

const UnitSet& reference = myMap.find("l")->second;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM