Open In App

How to Find the First Element in a Set in C++?

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

In C++, a set is a container that stores unique elements following a specific order. In this article, we will learn how to find the first element in a set.

Example:

Input:
mySet = {1, 2, 4, 3, 8, 4, 7, 8, 6, 4}

Output:
First Element = 1

Find the First Element in a Set in C++

To find the first element in a std::set in C++, we can use the std::set::begin() function that returns an iterator pointing to the first element of the set. We can dereference this iterator to get the first element in the set.

C++ Program to Find the First Element in a Set

C++




// C++ Program to Find the First Element from vector
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    set<int> mySet = { 3, 1, 4, 1, 5, 9, 2, 6 };
  
    // Finding the first element in the set
    auto firstElement = mySet.begin();
  
    cout << "First element: " << *firstElement << endl;
  
    return 0;
}


Output

First element: 1

Time complexity: O(1)
Space complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads