How to Find All Occurrences of an Element in a Set in C++?
Last Updated :
29 Feb, 2024
Finding the all occurrences of a specific element in a set using the C++ STL is a very efficient process that is done with the help of std::set::distance() member function. In this article, we’ll explore how to find the first element in a set using the C++ STL.
For Example,
Input:
mySet = {1, 2, 4, 3, 8, 4, 7, 8, 6, 4}
Element = 4
Output:
Index = 2 because occurrences of any element in a set is always 1, so consider the first Occurence of the elment.
Find all Occurrences of a Specific Element in std::set in C++
To find all occurrences of a specific element from a set in C++, we can iterate over the set and print the indices where the target integer is found.
Note: Occurrences of any element in a set is always 1. so the first Occurence will be the Last Occurrence of the element in set.
C++ Program to Find All Occurrences of an Element in a Set
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
std::set< int > mySet
= { 1, 2, 3, 4, 1, 5, 1, 6, 7, 8, 1 };
int target = 4;
bool found = false ;
cout << "Element " << target << " found at indices: " ;
size_t index = 0;
for ( auto it = mySet.begin(); it != mySet.end();
++it, ++index) {
if (*it == target) {
cout << index << " " ;
found = true ;
}
}
if (!found) {
cout << "Element " << target
<< " not found in the set.\n" ;
}
return 0;
}
|
Output
Element 4 found at indices: 3
Time complexity: O(logN), where N is the number of elements in the setl.
Space complexity: O(1)
Share your thoughts in the comments
Please Login to comment...