How to traverse a C++ set in reverse direction


Given a Set, the task is to traverse this Set in reverse order.

Examples:

Input: set = [10 20 30 70 80 90 100 40 50 60]
Output: 100 90 80 70 60 50 40 30 20 10 

Input: set = [1 2 3 4 5]
Output: 5 4 3 2 1

Approach:
To traverse a Set in reverse order, a reverse_iterator can be declared on it and it can be used to traverse the set from the last element to the first element with the help of rbegin() and rend() functions.

  1. Get the set.
  2. Declare the reverse iterator on this set.
  3. Traverse the set from the last element to the first element with the help of rbegin() and rend() functions.

Below is the implementation of the above approach:

Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Get the set
    int arr[] = { 14, 12, 15, 11, 10 };
  
    // initializes the set from an array
    set<int> s(arr, arr + sizeof(arr) / sizeof(arr[0]));
  
    // declare iterator on set
    set<int>::iterator it;
  
    cout << "Elements of Set in normal order:\n";
  
    // prints all elements in normal order
    // using begin() and end() methods
    for (it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
  
    // declare reverse_iterator on set
    set<int>::reverse_iterator rit;
  
    cout << "\nElements of Set in reverse order:\n";
  
    // prints all elements in reverse order
    // using rbegin() and rend() methods
    for (rit = s.rbegin(); rit != s.rend(); rit++)
        cout << *rit << " ";
  
    return 0;
}

chevron_right


Output:

Elements of Set in normal order:
10 11 12 14 15 
Elements of Set in reverse order:
15 14 12 11 10


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.