I have a member function that compares data in a C++ map. I declared the member functio开发者_高级运维n 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;
精彩评论