Jack BeNimble Jack BeNimble - 1 year ago 106
C++ Question

how to iterate in reverse over a map in c++

I'm having trouble iterating in reverse over a map in gcc c++. When I use a reverse iterator, it seems I can't assign anything to it - the compiler complains. I'm working around it with some awkward code using a forward iterator, but it's not very elegant. Any thoughts?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download