C++ Standard Library C++ STL Library

C++ map - count() Function



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

Syntax

size_type count (const key_type& k) const;
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 map, else returns 0.

Time Complexity

Logarithmic i.e, Θ(log(n)).

Example:

In the example below, the map::count function is used to check the presence of specified key in the map called MyMap.

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

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

The output of the above code will be:

103 is a key of MyMap.
104 is a key of MyMap.
105 is a key of MyMap.
106 is not a key of MyMap.
107 is not a key of MyMap.

❮ C++ <map> Library