ORIGIN

Whether key value in MAP exists

C++ 1 min122 words

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

find function returns an iterator.

1
2
3
4
5
map<int, int> test;

if(test.find(key) == test.end()) {
// the key doesn't exists
}

Count Function

1
2
3
if(test.count(key) == 0) {
// the key doesn't exists
}
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|