Open In App

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

Last Updated : 08 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Share
4 Likes
Like
Report

In C++, elements of a set cannot be accessed directly by index or position. However, we can work around this limitation using iterators. In this article, we will learn how to access the elements in set by index in C++.

The most efficient way to access a set element by index is to use the std::next() function. Let's take a look at a simple example:


Output
6

Explanation: next() function returns the set::begin() iterator incremented by i times. We have dereferenced this iterator to access the value.

Note: The next() function does not modify the given iterator. It returns the incremented copy of the iterator.

There are also some other methods in C++ to access elements in a set by index, but they all use same concept.

Using advance() Function

The std::advance() can also be used to access the set element at some given index in the same way as next() function, but this function modifies the given iterator.


Output
6

Incrementing Using Loops

Increment the set::begin() iterator i number of times using a loop. This will make it point to the element at the given index.


Output
6

This is how both the next() and advance() functions are internally implemented with some minor changes.


Next Article

Similar Reads