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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With