Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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
like image 697
Cheok Yan Cheng Avatar asked Dec 13 '22 23:12

Cheok Yan Cheng


2 Answers

The reason is that std::map semantics state that if you try to access an element at a key that does not exist, the key is created with a default-constructed element. In other words m[0] will create an int at location 0 if one does not already exist. Obviously, that is not compatible with a const map.

You could say "well, make a const version of operator[] and have it not do that!", but there are two problems: the difference in semantics would be non-obvious and confusing, and it's not clear exactly what should happen if you do try to access a key that does not exist (throw an exception?).

Instead, what you should do is use the find() method on the map, which will return an iterator pointing to the key/value pair you're looking for. The lookup is exactly as efficient as operator[], it can be used on const maps (returning a const iterator in that case), and it will return the end() iterator if the key does not exist.

like image 143
Tyler McHenry Avatar answered Dec 15 '22 13:12

Tyler McHenry


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.

like image 28
Vijay Mathew Avatar answered Dec 15 '22 14:12

Vijay Mathew