Incrementing non-existent map entries

Viewed 43

I understand that if you reference a map entry that doesn't exist, the map::operator[] searches the map for a value corresponding to the given key, and returns a reference to it. If it can't find one it creates a default constructed element for it. That being said, what happens in the case below where one attempts to increment a non-existent key in a map? What would the value for the key end up being? i.e.

map<string,int> m;
...
string s = "dog"

m["dog"]++
1 Answers

In the example you gave, you increment the value, not the key. That is, m[dog]++ will affect the value itself. If the given key does not exist, the map will first insert a key-value pair with zero initialized or default constructed value and then there will be an attempt to apply operator++ to the value. If this operator is not defined for the value, compilation fails. In case of the value being int, you end up having a "dog" key corresponding to 1.

If you want to increment the key, you should apply increment to the key. And here, first of all, you should consider the difference between post and pre increment. That is, when you do something like:

m[dog++];

the key only gets incremented after you call the operator[] which means this increment has no effect at all. If you want this increment to affect the call, use pre increment.

Secondly, make sure the type of the key you use has an overloaded operator++. Strings do not, so this code won't compile at all.

So, the only case increment can take place is when you use pre increment and the operator++ is defined for the type you use as a key. Provided key is of some integral type, you consider this:

int key = 0;
m[++key];

In this case, if the key 1 does not exist, the map will insert a new pair with the key being 1 and a zero initialised or default constructed value.

Related