HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

C++11 reverse range-based for-loop

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
reverseforrangeloopbased

Problem

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) { ...


into this:

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


I want to convert this:

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


to this:

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


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

Solution

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

#include 
#include 
#include 

int main()
{
    std::list 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';
}

Code Snippets

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

Context

Stack Overflow Q#8542591, score: 284

Revisions (0)

No revisions yet.