Normally, if I want to find whether the key exists in map STL(C++), the first thing come up to my mind is if(map1[key1])
. However, this is wrong, because if there is no key equals to key1
, map1[key1]
will return 0 and if there is a key1
but its value is 0
, then it will also return 0; So this method is not feasible.
There are generally two ways to determine whether the key exists in map.
find function returns an iterator.
1 | map<int, int> test; |
1 | if(test.count(key) == 0) { |