How to Access an Element in Set in C++?
Last Updated : 12 Feb, 2024
Improve
In C++ STL (Standard Template Library), the set container represents a collection of unique, sorted elements. In this article, we will see how to an element in a set in C++ using iterators.
Example
Input: mySet = {1, 8, 99, 444, 521 } Output: mySet Value at Index 2: 99
Access an Element in a Set in C++
We can use the set iterators provided by the function std::set::begin() to access the elements of a set. Iterators are like pointers, we can access any index value using this iterator by incrementing and decrementing.
Note: While using the iterator, be careful not to go out of bounds.
C++ Program to Access an Element in a Set using Iterators
Below is the Implementation of the above approach:
// C++ program for accessing the element of the set using
// iterator
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main()
{
// Create set
set<int> mySet;
// Populate the set
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(40);
mySet.insert(50);
// Using iterators access the desired element
set<int>::iterator it = mySet.begin();
it++;
it++;
// Print the desired element
cout << "Third element in the set (Using Iterators): "
<< *(it) << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Output
Third element in the set (Using Iterators): 30
Time Complexity: O(logN)
Auxiliary Space: O(1)