How to Find the Frequency of an Element in a Set in C++?
Last Updated :
28 Feb, 2024
C++ STL provides a set container that can be used to store unique elements in a sorted order. In this article, we will learn how to find the frequency of an element in a set in C++.
Example:
Input:
set<int>s ={10,20,30,40,50}
Output:
Frequency of 30 is 1
Finding Frequency of an Element in a Set in C++
In C++, the set stores the unique element, so if the element is present in the set, its frequency cannot be more than 1. But std::set still has the std::set::count() function that can be used to find the frequency of a specific element. This function returns 0 if the element is not present and 1 if the element is present.
C++ Program to Find the Frequency of an Element in a Set
The below example demonstrates how we can find the frequency of a specific element in a set.
C++
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 10, 20, 30, 20, 40, 20, 50 };
cout << "Set Elements: " ;
for ( auto it : mySet) {
cout << it << " " ;
}
cout << endl;
int targetElement = 30;
int frequency = mySet.count(targetElement);
cout << "Frequency of " << targetElement
<< " is: " << frequency << endl;
return 0;
}
|
Output
Set Elements: 10 20 30 40 50
Frequency of 30 is: 1
Time Complexity: O(N), where N is the total number of elements in the set.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...