Why does std::map not have a const accessor?

As of C++11 there is std::map::at which offers const and non-const access.

In contrast to operator[] it will throw an std::out_of_range exception if the element is not in the map.


operator[] in a map returns the value at the specified key or creates a new value-initialized element for that key if it's not already present, so it would be impossible.

If operator[] would have a const overload, adding the element wouldn't work.

That answers the question. Alternatives:

For C++03 - you can use iterators (these are const and non-const coupled with find). In C++11 you can use the at method.


These answers are correct in that operator[] has semantics to add a key if it doesn't exist, but I'd like to add another perspective:

Notice how operator[] returns a T&. That is, it returns a reference to the value that is associated with key. But what if there is no key in the map? What should we return? There's no such thing as a "null-reference," and throwing an exception would be annoying.

This would be one good reason for no operator[] const. What would you return to the user if you couldn't add anything to the map (because the operator is const), but they are looking for an item that doesn't exist? A good solution to this problem is to not have the operator[] const.


The (non-const) operator[] creates the key if it doesn't exist.

The const version of that operator, if it existed, would have to have different semantics, since it wouldn't be able to add a new key.

I am sure you would agree that having const and non-const overloads with significantly different semantics would be a can of worms. Therefore no const version is provided.

There is a const find() member though, so you can use that in your code.


Because the semantics of operator[] are to add the key if it doesn't exist.