Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Alex B Avatar asked Dec 17 '11 04:12

Alex B


1 Answers

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'; } 
like image 190
kennytm Avatar answered Sep 29 '22 09:09

kennytm