How to Traverse a Set with reverse_iterator in C++?
Last Updated :
21 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
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 << ", " ;
}
}
int main()
{
set< int > set1;
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);
display(set1);
return 0;
}
|
Output
100, 90, 80, 70, 60, 50, 40, 30, 20, 10,
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...