Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

map

stl

stdmap

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()?

like image 620
dolphy Avatar asked Aug 25 '14 16:08

dolphy


People also ask

How do you check if an element exist in map or not?

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 !=

How do you see if a value exists in a map C++?

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).

Which function is used to check if a key exists in map or not?

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.

What does count function do in 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.


1 Answers

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.

like image 55
Kerrek SB Avatar answered Oct 22 '22 18:10

Kerrek SB