How to Find the Frequency of an Element in a Set in C++? (original) (raw)

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:
sets ={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:📐: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++ `

// C++ program to illustrate how to find the frequency of a // specific element in a set #include #include #include using namespace std;

int main() {

// Intializing a  set with few elements
set<int> mySet = { 10, 20, 30, 20, 40, 20, 50 };

// Print the elements of the set
cout << "Set Elements: ";
for (auto it : mySet) {
    cout << it << " ";
}
cout << endl;

// Choose target element
int targetElement = 30;

// Use the count function to find the frequency of the
// target element
int frequency = mySet.count(targetElement);

// Output the frequency of the target element
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)

Similar Reads