In C++, how to iterate array in reverse using for_each?

user350954 picture user350954 · Sep 1, 2013 · Viewed 9k times · Source

In C++11, using lambda/for_each, how do we iterate an array from end?

I tried the following, but both result in infinite loop:

for_each (end(A), begin(A), [](int i) {
   ....
});

for_each (A.rend(), A.rbegin(), [](int i) {
    ...
});

Any idea? Thanks.

Answer

P0W picture P0W · Sep 1, 2013

You missed this ?

Flip your rbegin & rend

for_each (A.rbegin(), A.rend(), [](int i) {
    ...
});

Increasing reverse iterator moves them towards the beginning of the container