What is the unordered_map::count() function in C++?
The unordered_map::count() function is available in the <unordered_map> header file in C++.
The unordered_map::count() is used to count the number of elements in an unordered map with the specified key. The Unordered map does not allow repetition that’s why this method will return the count to be either or .
Syntax
The syntax of the unordered_map::count() function is given below:
boolean count(K key);
Function parameter(s)
The unordered_map::count() method accepts the parameters mentioned below:
- Key: The key whose count needs to be returned in the unordered map.
Return
The unordered_map::count() returns one of the two values:
- True (1): If the specified key element is present in the unordered map, the function returns a value of which can also be treated as a boolean
true. It return because the unordered map does not allow repetition of elements. - False (0): If the specified key element is not present in the unordered map, the function returns a value of which can also be treated as a boolean
false. It return because the unordered map does not allow repetition of elements.
Code
Let us have a look at the code now.
#include <iostream>#include <unordered_map>using namespace std;int main(){// Initialising unordered mapunordered_map<int,string> umap ={{12, "unordered"},{16, "map"},{89, "in"},{66, "C++"}};// Using unordered_map::count() functionif(umap.count(66))cout<<"The element with specified key is present."<<endl;elsecout<<"The element with specified key is absent."<<endl;return 0;}
Explanation of the code above
- In lines # 1 and 2, we imported the required header files.
- In line # 5, we made a
main()function. - From lines # 8-13, we initialized an unordered map with integer type keys and string type values.
- In lines 16-19, we used
unordered_map::count()function to check the presence of the element with the specified key and displayed the message accordingly.
In this way, you can quickly check whether the element is already present in the map or not using the count() function.
Free Resources
Attributions:
- undefined by undefined