39

I have a custom container class and defined iterators, so I can do:

for (auto i : c)

but is there something to iterate in reverse direction?

Something like:

for_reverse (auto i : c)
17
  • 14
    If you want to use boost: for (auto i : c | reversed) or for (auto i : reversed(c)) -- see boost.adaptors.reversed
    – leemes
    Feb 2, 2014 at 11:38
  • 3
    @leemes y u no answer.
    – user1804599
    Feb 2, 2014 at 11:39
  • 14
    @leemes: Wow, Boost's abuse of operator overloads never ceases to amaze me ;) Feb 2, 2014 at 11:39
  • 2
    You could always write a wrapper template to expose rbegin() and rend() and begin() and end().
    – WhozCraig
    Feb 2, 2014 at 11:44
  • 2
    @KonradRudolph If you do so: always ask yourself if your code is still self-explanatory for readers not knowing your library. I guess then you're definitely on the safe side.
    – leemes
    Feb 2, 2014 at 12:10

2 Answers 2

42
  1. You can use boost:

    #include <boost/range/adaptor/reversed.hpp>
    
    using namespace boost::adaptors;
    for (auto i : c | reversed)
        ...
    

    Or if you don't like operator overloading:

    #include <boost/range/adaptor/reversed.hpp>
    
    using namespace boost::adaptors;
    for (auto i : reverse(c))
        ...
    
  2. You can define a similar helper function using std::reverse_iterator so you don't depend on boost:

    template<typename It>
    class Range
    {
        It b, e;
    public:
        Range(It b, It e) : b(b), e(e) {}
        It begin() const { return b; }
        It end() const { return e; }
    };
    
    template<typename ORange, typename OIt = decltype(std::begin(std::declval<ORange>())), typename It = std::reverse_iterator<OIt>>
    Range<It> reverse(ORange && originalRange) {
        return Range<It>(It(std::end(originalRange)), It(std::begin(originalRange)));
    }
    

    Then you can write:

    for (auto i : reverse(c))
        ...
    

    Example

6
  • 1
    I really liked the self-implemented solution and I actually learned something about C++11. Thanks!! +1 :)
    – Marco A.
    Feb 2, 2014 at 12:20
  • 1
    Is there a reason to use std::end and std::begin, rather than std::rbegin and std::rend? / Edit: just saw your comment regarding this on bobah's answer. Not sure I really agree with it, but it is at least the answer to my question. :) Feb 2, 2014 at 13:36
  • @LightnessRacesinOrbit Very simple: they are introduced in C++14... Not sure why you should not agree with it ;)
    – leemes
    Feb 2, 2014 at 13:49
  • @leemes: Oh yeah :( I was thinking of std::vector::rbegin (and friends) which date back to C++98. You could still make use of them here for those containers which support it, but meh Feb 2, 2014 at 13:50
  • @LightnessRacesinOrbit As you see in the history, I first used the member functions. But then I wanted to add support for raw arrays to mirror the compatibility of the "normal" usage of range-based for.
    – leemes
    Feb 2, 2014 at 13:51
10

A one-off pain

namespace details {
    template <class T> struct _reversed { T& t; _reversed(T& _t): t(_t) {} };
}

template <class T> details::_reversed<T> reversed(T& t) { return details::_reversed<T>(t); }
template <class T> details::_reversed<T const> reversed(T const& t) { return details::_reversed<T const>(t); }

namespace std {
    template <class T> auto begin(details::_reversed<T>& r) -> decltype(r.t.rbegin()) { return r.t.rbegin(); }
    template <class T> auto end(details::_reversed<T>& r) -> decltype(r.t.rend()) { return r.t.rend(); }

    template <class T> auto begin(details::_creversed<T> const& cr) -> decltype(cr.t.rbegin()) { return cr.t.rbegin(); }
    template <class T> auto end(details::_creversed<T> const& cr) -> decltype(cr.t.rend()) { return cr.t.rend(); }
}

and then you are able to do the below

for (auto x: reversed(c)) ...
7
  • As far as I can see, this requires T to implement rbegin() and rend(), which is not the case for simple custom container classes (you probably only want to implement begin() and end()) as well as for C-arrays. Regarding the latter, you could use std::rbegin and std::rend since C++14, or std::reverse_iterator with std::begin and std::end since C++11.
    – leemes
    Feb 2, 2014 at 12:12
  • @KonradRudolph - thanks, constancy should be fixed now
    – bobah
    Feb 2, 2014 at 12:21
  • 1
    Now your code is running afoul of C++ naming rules which make it illegal to start an identifier with an underscore in the global namespace. I know, no compiler diagnoses this, but it’s invalid nevertheless. Feb 2, 2014 at 13:04
  • @KonradRudolph - ok, one more step to ideal... fixed
    – bobah
    Feb 3, 2014 at 11:10
  • You are not allowed to add declarations to the std namespace, this code invokes undefined behaviour. Also, even then, in C++14 std is not an associated namespace anymore for range-for. Just drop those into the detail namespace. Lastly, you don't need '_creversed'. If T is const, the normal _reversed template works just as well.
    – Xeo
    Feb 3, 2014 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.