Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 870
user350954 Avatar asked Sep 01 '13 20:09

user350954


People also ask

How do you iterate over a vector in reverse order?

So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.

How do you iterate forEach backwards?

To use the forEach() method on an array in reverse order: Use the slice() method to get a copy of the array. Use the reverse() method to reverse the copied array.

How do you reverse an iterator?

C++ Iterators Reverse Iterators A reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base() . To iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.

What is Rbegin?

The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.


2 Answers

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

like image 73
P0W Avatar answered Oct 14 '22 08:10

P0W


Boost offers a feature named reversed, that can be used with C++ 11 range based for loop as describes Yakk in his answer:

for(int i : reverse(A))
{
  // code
}

or

for(int i : A | reversed)
{
  // code
}
like image 26
Vizor Avatar answered Oct 14 '22 06:10

Vizor