Open In App

How to Find First Occurrence of an Element in a Set in C++?

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to find the position of the first occurrence
// of a target element in a set
  
#include <iostream>
#include <set>
  
using namespace std;
  
int main()
{
    // Initialize a set
    set<int> mySet = { 1, 2, 4, 3, 8, 4, 7, 8, 6, 4 };
  
    // Initialize a target variable
    int target = 4;
  
    // Find the first occurrence of the target element
    auto it = mySet.find(target);
  
    // Check if the target element was found
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads