Why can't we have an immutable version of operator[] for map

c++, stl

Solution

operator[] will create the entry if it does not exist in the map. This is not possible if the operator is implemented for a const map. This is the explanation given in The C++ Programming Language:

Subscripting a map adds a default element when the key is not found. Therefore, there is no version of operator[] for const maps. Furthermore, subscripting can be used only if the mapped_type (value type) has a default value. If the programmer simply wants to see if a key is present, the find() operation (§17.4.1.6) can be used to locate a key without modifying the map.

Problem

The following code works fine : ``` std::map<int, int>& m = std::map<int, int>(); int i = m[0]; ``` But not the following code : ``` // error C2678: binary '[' : no operator... const std::map<int, int>& m = std::map<int, int>(); int i = m[0]; ``` Most of the time, I prefer to make most of my stuff to become immutable, due to reason : http://www.javapractices.com/topic/TopicAction.do?Id=29 I look at map source code. It has ``` mapped_type& operator[](const key_type& _Keyval) ``` Is there any reason, why std::map unable to provide ``` const mapped_type& operator[](const key_type& _Keyval) const ```

Original source