Related Tags

unordered map
c++
communitycreator

# What is the unordered_map::count() function in C++?

Harsh Jain

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 $1$ or $0$.

### 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 $1$ which can also be treated as a boolean true. It return $1$ 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 $0$ which can also be treated as a boolean false. It return $0$ 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 map
unordered_map<int,string> umap ={
{12, "unordered"},
{16, "map"},
{89, "in"},
{66, "C++"}
};

// Using unordered_map::count() function
if(umap.count(66))
cout<<"The element with specified key is present."<<endl;
else
cout<<"The element with specified key is absent."<<endl;

return 0;
}
Using unordered_map::count() function in C++

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

RELATED TAGS

unordered map
c++
communitycreator

CONTRIBUTOR

Harsh Jain