Horje
How to Traverse a Set with reverse_iterator in C++?

In C++, sets are a type of associative container in which each element has to be unique because the value of the element identifies it. It provides reverse iterators that make it easier to traverse the set in reverse direction. In this article, we will discuss how to traverse a set with reverse_iterator in C++.

Example

Input:
input_set = {70,10,50,90,60,40,100,30,20,80

Output:
100, 90, 80, 70, 60, 50, 40, 30, 20, 10

Traverse a Set with reverse_iterator in C++

Reverse iterators in C++ are used to traverse the set backward. The std::set has two member functions that provide the reverse iterators:

  • set::begin(): Return the reverse iterator pointing to the last element in the set.
  • set::rend(): Return a reverse iterator pointing to the theoretical element right before the first element in the set.

C++ Program to Traverse a Set with reverse_iterator

C++

// C++ program to traverse the set using the
// reverse_iterator.
#include <iostream>
#include <set>
using namespace std;
  
// Function to display elements of the set
// using reverse_iterator
void display(set<int> set1)
{
    set<int>::reverse_iterator r_itr;
    for (r_itr = set1.rbegin(); r_itr != set1.rend();
         r_itr++) {
        cout << *r_itr << ", ";
    }
}
// Driver Code
int main()
{
    // Create an empty set
    set<int> set1;
  
    // Insert 10 elements into the set
    set1.insert(70);
    set1.insert(10);
    set1.insert(50);
    set1.insert(90);
    set1.insert(60);
    set1.insert(40);
    set1.insert(100);
    set1.insert(30);
    set1.insert(20);
    set1.insert(80);
  
    // Call the display() function
    display(set1);
  
    return 0;
}

Output

100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 

Time Complexity: O(N)
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Traverse a Set with const_iterator in C++? How to Traverse a Set with const_iterator in C++?
How to Find Union of Two Multisets in C++? How to Find Union of Two Multisets in C++?
How to Find Intersection of Two Multisets in C++? How to Find Intersection of Two Multisets in C++?
How to Concatenate Two Sets in C++? How to Concatenate Two Sets in C++?
How to Find the Size of a Map in C++? How to Find the Size of a Map in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13