C++ Standard Library C++ STL Library

C++ multimap - count() Function



The C++ multimap::count function returns the number of occurrences of a specified key in the multimap container.

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

Number of elements with specified key in the multimap container.

Time Complexity

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

Example:

In the example below, the multimap::count function is used to find out the number of occurrences of specified key in the multimap called MyMMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  multimap<string, string> MyMMap;
  multimap<string, string>::iterator it;

  MyMMap.insert(pair<string, string>("USA", "New York"));
  MyMMap.insert(pair<string, string>("USA", "Washington"));  
  MyMMap.insert(pair<string, string>("CAN", "Toronto"));
  MyMMap.insert(pair<string, string>("CAN", "Montreal"));
  MyMMap.insert(pair<string, string>("IND", "Delhi"));

  string MyStr[3] = {"CAN", "IND", "USA"};
  for(int i = 0; i < 3; i++) {
    string j = MyStr[i];
    cout<<"\nThere are "<<MyMMap.count(j)<<" elements with key "<<j<<": ";
    for(it = MyMMap.equal_range(j).first; it!=MyMMap.equal_range(j).second; it++)
      cout<<it->second<<" ";
  }
  return 0;
}

The output of the above code will be:

There are 2 elements with key CAN: Toronto Montreal 
There are 1 elements with key IND: Delhi 
There are 2 elements with key USA: New York Washington 

❮ C++ <map> Library