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

How can I iterate in reverse over a map in C++?(如何在 C++ 中反向迭代地图?)
本文介绍了如何在 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?

解决方案

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
Image Capture with OpenCV - Select Timeout Error(使用 OpenCV 捕获图像 - 选择超时错误)
SHA256 HMAC using OpenSSL 1.1 not compiling(使用 OpenSSL 1.1 的 SHA256 HMAC 未编译)
How to make a Debian package depend on multiple versions of libboost(如何制作一个Debian包依赖于多个版本的libboost)
Why does strcpy_s not exist anywhere on my system?(为什么我系统上的任何地方都不存在 strcpy_s?)
Simplest way to get current time in current timezone using boost::date_time?(使用 boost::date_time 在当前时区获取当前时间的最简单方法?)