In this article we will discuss how to access an element by index in a Set.

std::set is an associative container, which internally store elements in a balanced binary search tree and it doesn’t provide random access operator [].

Therefore accessing a random element from set by index is little tricky.

Accessing nth element in Set

Suppose we have a set of strings i.e.

Inside the set elements will be stores in sorted order i.e.

Now, to access an element at nth index we need to create an iterator pointing to starting position and keep on  increment the iterator till nth element is reached i.e.

But you don’t need to write this code again and again. STL provides two algorithms which serves the same purpose.

Accessing nth element using std::advance

std::advance accepts an iterator and  a value by which it  advances the given iterator.  Let’s see how to access 3rd element using std::advance

 

Accessing nth element using std::next

It is introduced in c++11, unlike std::advance it doesn’t increment the given iterator, instead it returns a new iterator that will be n position advanced to given iterator.
Let’s see how to access the 3rd element using std::next,

In all the above methods we need to check if n < size of set before calling std::next or std::advance i.e.

 

Creating generic method to access nth element from any set

Let’s create a generic method that will return the nth element and will also check for errorneous scenarios i.e. what if n > size i.e.

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.