How can I iterate in reverse over a map in C++?

前端 未结 2 1877
春和景丽
春和景丽 2021-02-06 23:14

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 aro

2条回答
  •  孤城傲影
    2021-02-06 23:22

    Here's an example of iterating backward through a std::map:

    #include 
    #include 
    #include 
    
    int main() {
        std::map 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::reverse_iterator
    

    Note that if you're using boost, you can use a range-based for loop with a reverse adapter:

    #include 
    
    for (auto& iter : boost::adaptors::reverse(m)) {
        std::cout << iter.first << ": " << iter.second << std::endl;
    }
    

提交回复
热议问题