How to Find the Frequency of an Element in a Multiset in C++?
Last Updated :
22 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
multiset< int > set = { 5, 2, 8, 5, 8 };
int element = 8;
int frequency = set.count(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++.
Share your thoughts in the comments
Please Login to comment...