如何在C ++中反向迭代地图 [英] how to iterate in reverse over a map in c++

查看:50
本文介绍了如何在C ++中反向迭代地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在gcc 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?

推荐答案

下面是通过std::map向后迭代的示例:

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;
    }
}

如果您是C ++ 11之前的版本,则只需要拼写auto,即:

If you are pre-C++11, you'll just need to spell out auto, which is:

std::map<std::string, std::string>::reverse_iterator

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

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;
}

这篇关于如何在C ++中反向迭代地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆