Open In App

How to Use a reverse_Iterator with a Map in C++?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a reverse_iterator is a type of iterator that points to elements in a container in the reverse order. This means that using a reverse_iterator, you can traverse a container from end to beginning. In this article, we will learn how to use a reverse_iterator with a map in C++.

Example:

Input:
myMap = {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}};

Output: 
Result: {{“cherry”, 3}, {“banana”, 2},  {“apple”, 1}};

Iterate Over a Map Using reverse_iterator in C++

We can get the reverse_iterator to the std::map container using the std::map::rbegin() and std::map::rend() functions that return a reverse_iterator pointing to the reverse beginning (i.e. last element) and the reverse end (i.e. hypothetical element before the first element) of the map, respectively. We can then use these iterators to reverse iterate the map.

C++ Program to Iterate Over a Map Using reverse_iterator

C++




// C++ Program to illustrate how to Iterate Over a Map Using
// reverse_iterator
#include <iostream>
#include <map>
using namespace std;
  
// Driver Code
int main()
{
    // Creating a map of string and int
    map<string, int> myMap = { { "apple", 1 },
                               { "banana", 2 },
                               { "cherry", 3 } };
  
    // Declaring a reverse_iterator to the map
    map<string, int>::reverse_iterator it;
  
    // Displaying map elements using reverse_iterator
    for (it = myMap.rbegin(); it != myMap.rend(); ++it) {
        cout << it->first << " " << it->second << endl;
    }
  
    return 0;
}


Output

cherry 3
banana 2
apple 1

Time Complexity: O(N), where N is the number of elements in the map.
Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads