How to Find First Occurrence of an Element in a Set in C++?
Last Updated :
16 Feb, 2024
In C++, a set is an ordered container that stores its unique values in some given order. In this article, we will see how to find the first occurrence of a specific element in a set in C++ STL.
For Example,
Input:
mySet = {1, 2, 3, 8, 9, 11}
Target = 9
Output:
Element found at Index: 4
Find the First Occurrence of an Element in a Set in C++
To find the first occurrence of a given element in a set, we can use the std::set::find() member function which returns the iterator to the first occurrence of the given element in the set. If the element is not found, it returns the iterator to the end.
Note: The std::set containers only store the unique the first occurrence will also be the only occurrence of the element in the set.
C++ Program to Find the First Occurrence of a Given Element
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 1, 2, 4, 3, 8, 4, 7, 8, 6, 4 };
int target = 4;
auto it = mySet.find(target);
if (it != mySet.end()) {
cout << "Element " << target
<< " found at position "
<< distance(mySet.begin(), it) << endl;
}
else {
cout << "Element " << target
<< " not found in the set." << endl;
}
return 0;
}
|
Output
Element 4 found at position 3
Time complexity: O(log n)
Space complexity: O(1)
Share your thoughts in the comments
Please Login to comment...