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

前端 未结 2 1875
春和景丽
春和景丽 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:30

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

提交回复
热议问题