How can I iterate in reverse over a map in C++?
Since C++20 you can make use of the range adaptor std::views::reverse
from the Ranges library. If you add this to a range-based for loop with structured binding, iterating backwards over an std::map
could be done as follows:
#include <map>
#include <ranges>
#include <iostream>
int main() {
std::map<std::string, int> m = { {"a", 1}, {"b", 2}, {"c", 3} };
for (auto const& [k, v] : m | std::views::reverse)
std::cout << k << " => " << v << std::endl;
return 0;
}
Output:
c => 3
b => 2
a => 1
Code on Wandbox
Here's an example of iterating backward through a std::map
:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> m;
m["a"] = "1";
m["b"] = "2";
m["c"] = "3";
for (auto iter = m.rbegin(); iter != m.rend(); ++iter) {
std::cout << iter->first << ": " << iter->second << std::endl;
}
}
If you are pre-C++11, you'll just need to spell out auto
, which is:
std::map<std::string, std::string>::reverse_iterator
Note that if you're using boost, you can use a range-based for loop with a reverse adapter:
#include <boost/range/adaptor/reversed.hpp>
for (auto& iter : boost::adaptors::reverse(m)) {
std::cout << iter.first << ": " << iter.second << std::endl;
}