C++ map access discards qualifiers (const)

std::map's operator [] is not declared as const, and cannot be due to its behavior:

T& operator[] (const Key& key)

Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist.

As a result, your function cannot be declared const, and use the map's operator[].

std::map's find() function allows you to look up a key without modifying the map.

find() returns an iterator, or const_iterator to an std::pair containing both the key (.first) and the value (.second).

In C++11, you could also use at() for std::map. If element doesn't exist the function throws a std::out_of_range exception, in contrast to operator [].


Since operator[] does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values.

Instead, you can use:

VALUE = map.find(KEY)->second;

or, in C++11, you can use the at() operator:

VALUE = map.at(KEY);