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()
?
You can call map::count(key) with a specific key; it will return how many entries exist for the given key. For maps with unique keys, the result will be either 0 or 1. Since multimap exists as well with the same interface, better compare with !=
To check if a key exists in a C++ map, you can use std::map::count. It returns 0 (the key is absent) or 1 (the key is present).
containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
The map::count() is a built-in function in C++ STL which returns 1 if the element with key K is present in the map container. It returns 0 if the element with key K is not present in the container. Parameters: The function accepts a mandatory parameter k which specifies the key to be searched in the map container.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With