How to check if std::map contains a key without doing insert?

jmasterx picture jmasterx · Oct 8, 2010 · Viewed 170.5k times · Source

The only way I have found to check for duplicates is by inserting and checking the std::pair.second for false, but the problem is that this still inserts something if the key is unused, whereas what I want is a map.contains(key); function.

Answer

Potatoswatter picture Potatoswatter · Oct 8, 2010

Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

Alternately my_map.find( key ) != my_map.end() works too.