In this article we will discuss different ways to iterate over a set in C++.

Let’s create a set of strings i.e.

Now let’s iterate over it and print the contents on screen using different methods i.e.

Iterating over a Set using Iterators

set::begin() returns an iterator pointing to the first element in set. Whereas, set::end() returns an iterator past the end of set.

Now to iterate a set in forward direction, we need to create an iterator and initialise it with set::begin(). So that it points to start of set and then we will keep on access and increment the iterator to next till set::end() is reached i.e.

Here we iterated the set in forward direction. Now, let’s see how to iterate in reverse direction.

Iterating a set in backward direction using reverse_iterator

set::rbegin() returns a reverse_iterator pointing to the last element of set. Whereas, set::rend() returns a reverse_iterator pointing to element before the first element.

Now to iterate a set in reverse direction, we need to create an reverse_iterator and initialise it with set::rbegin(). So that it points to the last element of set and then we will keep on access and increment the iterator to next till set::rend() is reached i.e. beginning of set.

 

Iterating over a set using Range base for loop

 

Iterating over a set using std::for_each and range based for loop

Complete example is as follows,

 

Output:

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,