C++ 如何在c ++中反向迭代地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/732160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:58:45  来源:igfitidea点击:

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

c++loopsfor-loop

提问by Hyman BeNimble

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?

我在 gcc c++ 中反向迭代地图时遇到了麻烦。当我使用反向迭代器时,似乎我无法为其分配任何内容 - 编译器抱怨。我正在使用前向迭代器处理一些笨拙的代码,但它不是很优雅。有什么想法吗?

回答by GManNickG

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

这是一个通过 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:

如果您是 C++11 之前的,您只需要拼出auto,即:

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:

请注意,如果您使用的是 boost,则可以使用带有反向适配器的基于范围的 for 循环:

#include <boost/range/adaptor/reversed.hpp>

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