How to implement reverse traversal in a C++ map?

In C++, reverse traversal of a map can be achieved by using the functions rbegin() and rend(). rbegin() returns a reverse iterator pointing to the last element in the map, while rend() returns a reverse iterator pointing to the beginning of the map.

Here is an example code demonstrating how to iterate through a map in reverse order:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;

    myMap[1] = "One";
    myMap[2] = "Two";
    myMap[3] = "Three";
    myMap[4] = "Four";
    myMap[5] = "Five";

    // 倒序遍历map
    for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }
    
    return 0;
}

The output is:

5: Five
4: Four
3: Three
2: Two
1: One

In this example, we have created a map object called myMap and inserted some key-value pairs into it. Then, we used the rbegin() and rend() functions to traverse the map in reverse order and output the keys and values of each key-value pair.

bannerAds