Open In App

How to Find the Frequency of an Element in a Multiset in C++?

In C++, a multiset is a container that stores elements in a sorted order and multiple elements can have the same values. In this article, we will learn how to find the frequency of a specific element in a multiset.

Example:



Input:
myMultiset = { 5,2,8,5,8,8}
Element: 8

Output: 
Frequency of 8 is: 3

Finding Frequency of an Element in Multiset in C++

To find the frequency of a specific element in a std::multiset in C++, we can use the std::multiset::count() function that returns the number of times the given element occurs within the multiset.

C++ Program to Find the Frequency of an Element in a Multiset

The below example demonstrates the use of multiset::count() function to find the frequency of a specific element in a multiset in C++.






// C++ Program to find the frequency of a specific Element
// in a Multiset in C++ STL
  
#include <iostream>
#include <set>
using namespace std;
int main()
{
    // multiset declaration
    multiset<int> set = { 5, 2, 8, 5, 8 };
  
    // Element to find frequency
    int element = 8;
  
    // finding the frequency of specific element
    int frequency = set.count(element);
  
    // Printing the frequency of specific element
    cout << "Frequency of " << element
         << " in the multiset: " << frequency << endl;
  
    return 0;
}

Output
Frequency of 8 in the multiset: 2

Time Complexity: O(log(N))
Auxilliary Space: O(1)

Note: We can also use the multiset::find() function or multiset::equal_range() function to find the frequency of specific element in a multiset in C++.

Article Tags :