Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ map::count function is used to return 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 below example, 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 an element of MyMap.\n";
    else
      cout<<i<<" is an element of MyMap.\n";
  }
  return 0;
}

The output of the above code will be:

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

❮ C++ - Map