C++ Standard Library C++ STL Library

C++ unordered_multimap - count() Function



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

Syntax

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 unordered_multimap container.

Time Complexity

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

Example:

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

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_multimap<string, string> uMMap;
  unordered_multimap<string, string>::iterator it;

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

  string MyStr[3] = {"CAN", "IND", "USA"};
  for(auto& i: {"CAN", "IND", "USA"})
    cout<<"There are "<<uMMap.count(i)<<" elements with key "<<i<<".\n";

  return 0;
}

The output of the above code will be:

There are 2 elements with key CAN.
There are 1 elements with key IND.
There are 2 elements with key USA.

❮ C++ <unordered_map> Library