How to Find the First Element in a Set in C++? (original) (raw)

Last Updated : 26 Feb, 2024

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:📐: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 #include using namespace std;

int main() { set 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;

}

`

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

Similar Reads