Checking for existence in std::map - count vs find

dolphy picture dolphy · Aug 25, 2014 · Viewed 28.7k times · Source

So there seem to be two generally acceptable methods of determining whether or not a key exists in a std::map:

map.find(key) != map.end()
map.count(key) > 0

Is one more efficient than the other? Specifically, the concept of count() could be interpreted to mean that the method will iterate over every key, tallying a total count (and because of the definition of std::map, that total count will always be 0 or 1). Is count() guaranteed to "stop" after a match, operating at the same complexity as a find()?

Answer

Kerrek SB picture Kerrek SB · Aug 25, 2014

Since a map can only have at most one key, count will essentially stop after one element has been found. However, in view of more general containers such as multimaps and multisets, find is strictly better if you only care whether some element with this key exists, since it can really stop once the first matching element has been found.

In general, both count and find will use the container-specific lookup methods (tree traversal or hash table lookup), which are always fairly efficient. It's just that count has to continue iterating until the end of the equal-range, whereas find does not. Moreover, your code should document intent, so if you want to find something, use find.