How to Access an Element in Set in C++?
Last Updated :
12 Feb, 2024
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++
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main()
{
set< int > mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(40);
mySet.insert(50);
set< int >::iterator it = mySet.begin();
it++;
it++;
cout << "Third element in the set (Using Iterators): "
<< *(it) << endl;
return 0;
}
|
Output
Third element in the set (Using Iterators): 30
Time Complexity: O(logN)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...