Open In App

How to Find Frequency of a Key in a Multimap in C++?

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, Multimap is similar to a map that stores the data in the key-value format but the difference between these two containers is that we can have multiple elements with the same keys. In this article, we will learn how to find the frequency of a specific key in a multimap in C++.

Example

Input: 
multi_map = {{10,"A"},{10,"B"},{10,"C"},{5,"A"},{10,"D"},{4,"C"}}
Key = 10

Output:
Frequency of Key 10 is 4

Frequency of a Key in a Multimap in C++

The std:::multimap::count function in C++ STL is used to find the total number of key occurrences present in the multimap. It takes the key as a parameter and returns the integer that represents the total occurrences.

C++ Program to Find the Frequency of a Specific Key in a Multimap.

The below example demonstrates how we can use the std::count function to find the frequency of a specific key in a multimap in C++ STL.

C++




// C++ program to illustrate how to find the frequency of
// Specific key in Multimap
#include <iostream>
#include <map>
using namespace std;
int main()
{
  
    // creating a multimap
    multimap<int, string> multimap1
        = { { 10, "A" }, { 10, "B" }, { 10, "C" },
            { 5, "A" },  { 10, "D" }, { 4, "C" } };
  
    int key = 10;
    // printing the frequency of given key
    cout << "Frequency of Key " << key << " is "
         << multimap1.count(key);
    return 0;
}


Output

Frequency of Key 10 is 4

Time complexity: O(logN)
Auxilliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads