How to traverse a C++ set in reverse direction?


Suppose we have a set, then we have to traverse the set in reverse direction. So if the set is like S = [10, 15, 26, 30, 35, 40, 48, 87, 98], then the output will be: 98 87 48 40 35 30 26 15 10.

To traverse in reverse order, we can use the reverse_iterator. Here we will use the rbegin() and rend() function to get the begin and end of the reverse iterator.

Example

 Live Demo

#include <iostream>
#include <set>
using namespace std;
int main() {
   int arr[] = {10, 15, 26, 30, 35, 40, 48, 87, 98};
   set<int> my_set(arr, arr + sizeof(arr) / sizeof(arr[0]));
   set<int>::iterator it;
   cout << "Elements of Set in forward order: ";
   for (it = my_set.begin(); it != my_set.end(); it++)
      cout << *it << " ";
   set<int>::reverse_iterator rev_it;
   cout << "\nElements of Set in reverse order: ";
   for (rev_it = my_set.rbegin(); rev_it != my_set.rend(); rev_it++)
      cout << *rev_it << " ";
}

Output

Elements of Set in forward order: 10 15 26 30 35 40 48 87 98
Elements of Set in reverse order: 98 87 48 40 35 30 26 15 10

Updated on: 17-Dec-2019

908 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements