Search code examples
c++c++11ranged-loops

C++11 reverse range-based 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) { ...

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