C++ Standard Library C++ STL Library

C++ unordered_map - count() Function



The C++ unordered_map::count function returns the number of occurrences of a specified key in the unordered_map container. As an unordered_map contains unique keys, hence the function returns either 1 if the key is present in the unordered_map or 0 otherwise.

Syntax

size_type count (const key_type& k) const;

Parameters

k Specify key to search for.

Return Value

1 if the key is present in the unordered_map, else returns 0.

Time Complexity

Average case: Linear in number of elements counted.
Worst case: Linear in container size.

Example:

In the example below, the unordered_map::count function is used to check the presence of specified key in uMap.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_map<int, string> uMap;
  unordered_map<int, string>::iterator it;
  
  uMap[101] = "John";
  uMap[102] = "Marry";
  uMap[103] = "Kim";
  uMap[104] = "Jo";
  uMap[105] = "Ramesh";

  for(int i=103; i<108; i++)
  {
    if(uMap.count(i)==0)
      cout<<i<<" is not an element of uMap.\n";
    else
      cout<<i<<" is an element of uMap.\n";
  }
  return 0;
}

The output of the above code will be:

103 is an element of uMap.
104 is an element of uMap.
105 is an element of uMap.
106 is not an element of uMap.
107 is not an element of uMap.

❮ C++ <unordered_map> Library

5