Search code examples
c++11stlstdarray

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


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.


Solution

  • 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