Reputation: 41
I am aware that the map dereference operator[]
is not const
and can modify the map. However, I was wondering what happens when the operator is on the right side. For instance:
std::map<int, int> a;
int b = a[0];
Since a
will not have the 0
entry will this create a new entry in the map with the key 0
?
Upvotes: 2
Views: 646
Reputation: 420
Yes, map will create a new entry with key 0 and value 0 in your case.
Below is the description of operation [] in http://www.cplusplus.com/reference/map/map/operator[]/
mapped_type& operator[] (const key_type& k);
If k matches the key of an element in the container, the function returns a reference to its mapped value.If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value.
And sometimes it will introduce upexpected behavior if people forget the operator [] will insert a new key-value pair when it doesn't exist in the map. For example, below is a usural mistake.
std::map<int,int> my_map;
//check if 100 is in my_map
if ( my_map[100] ) {
//some code
}
I just want to check whether 100 is in my_map or not, but above code will insert a new key-value in my_map. So in this case, I should use find instead of operator [] if I just want to check 100.
std::map<int,int> my_map;
//check if 100 is in my_map
if ( my_map.find(100) != my_map.end() ) {
//some code
}
Upvotes: 1
Reputation: 4637
Regarding operator[]
:
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
From here, emphasis mine.
This is easy to test, too.
std::map<int, int> a;
std::cout << a.size(); //0
int b = a[0];
std::cout << a.size(); //1
Live example: http://ideone.com/z7PIRx
Upvotes: 6