C ++ 11反向基于范围的for-loop [英] C++11 reverse range-based for-loop

查看:695
本文介绍了C ++ 11反向基于范围的for-loop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个容器适配器会颠倒迭代器的方向,所以我可以反过来使用基于范围的for-loop迭代容器。

Is there a container adapter that would reverse the direction of iterators so I can iterate over a container in reverse with range-based for-loop?

使用显式迭代器我会转换这个:

With explicit iterators I would convert this:

for (auto i = c.begin(); i != c.end(); ++i) { ...

for (auto i = c.rbegin(); i != c.rend(); ++i) { ...

我要转换:

for (auto& i: c) { ...

到此:

for (auto& i: std::magic_reverse_adapter(c)) { ...

有没有这样的事情,还是我自己写的?

Is there such a thing or do I have to write it myself?

推荐答案

Actually Boost确实有这样的适配器: boost :: adapters :: reverse

Actually Boost does have such adaptor: boost::adaptors::reverse.

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

int main()
{
    std::list<int> x { 2, 3, 5, 7, 11, 13, 17, 19 };
    for (auto i : boost::adaptors::reverse(x))
        std::cout << i << '\n';
    for (auto i : x)
        std::cout << i << '\n';
}

这篇关于C ++ 11反向基于范围的for-loop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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