Iterating the Set

This is the most common way to access any element in the set by index. In this method, we will traverse the set using for loop and access any element. For accessing the nth index we will initialize an iterator for the given set and then we will iterate it n times to get to the nth index.

Example:

C++




// C++ program to access
// element by index in set.
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    set<int> s;
 
    // Inserting values in set
    s.insert(10);
    s.insert(20);
    s.insert(30);
    s.insert(40);
    s.insert(50);
     
    // Index(considering 0 as starting index)
    int n=3;
     
    // Initializing iterator
    auto it = s.begin();
     
    // Traversing the iterator till
    // nth index
    for(int i=0;i<n;i++)
    {
        it++;
    }
     
    // Printing the element at index n
    cout<<*it;
 
    return 0;
}


Output

40

How to Access Elements in Set by Index in C++?

Sets are the containers that are available in the C++ Standard Template Library (STL). They are used to hold distinct elements in a predetermined sequence; fundamentally, it operates on the same principles as a binary search tree

In C++, elements can be added to or removed from sets, but they cannot be modified after being stored there since their values become constant. The following methods are available to access elements in a set by index in C++ STL:

  • Accessing the element by iterating in the set.
  • Accessing the element at a particular index using the next() function.
  • Accessing the element at a particular index using the advance() function.
  • By Creating Generic methods to access the nth element from any set

Similar Reads

1. Iterating the Set

This is the most common way to access any element in the set by index. In this method, we will traverse the set using for loop and access any element. For accessing the nth index we will initialize an iterator for the given set and then we will iterate it n times to get to the nth index....

2. Using the next() function

...

3. Using the advance() function

Another way to access the element at any index is by using the next() function. This method is similar to the previous one, just we are using the next() function directly instead of loops to iterate....

4. Generic method to access the nth element

...

Contact Us