In the case of unordered_map in C++, what is the main difference between:
- if(map.find(n) != map.end())
- if(map.count(n) > 0)
- if(map[n] > 0)
Consider map is an unordered_map of type <int,int>.
In the case of unordered_map in C++, what is the main difference between:
Consider map is an unordered_map of type <int,int>.
These lines:
if(map.find(n) != map.end())
if(map.count(n) > 0)
Are mostly equivalent. map::count
will never return more than 1
.
This line:
if(map[n] > 0)
Loads the value
associated with the key, n
and compares if it's value is greater than zero. Not the same thing as the first two. map[n]
also has a side effect. If n
is not already a key in the map, the map will create a new value ("default initialized" or "zero-init" value) for that key. Hence, it can increase the size of the map implicitly.