The declaration for the [] operator on a std::map is this:
T& operator[] ( const key_type& x );
Is there a reason it isn't this?
T& operator[] ( const key_type& x );
const T& operator[] const ( const key_type& x );
Because that would be incredibly useful any time you need to access a member map in a const method.
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.