Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating backward

Suppose I have a vector<int> myvec and I want to loop through all of the elements in reverse. I can think of a few ways of doing this:

for (vector<int>::iterator it = myvec.end() - 1; it >= myvec.begin(); --it)
{
    // do stuff here
}

for (vector<int>::reverse_iterator rit = myvec.rbegin(); rit != myvec.rend(); ++rit)
{
    // do stuff here
}

for (int i = myvec.size() - 1; i >= 0; --i)
{
    // do stuff here
}

So my question is when should I use each? Is there a difference? I know that the first one is dangerous because if I pass in an empty vector, then myvec.end() - 1 is undefined, but are there any other hazards or inefficiencies with this?

like image 963
MBennett Avatar asked Mar 30 '10 21:03

MBennett


People also ask

What is backwards iteration?

This method involves slicing the list which starts from the position -1 and go backwards till the first position. We use a for loop with an iterator used as the index of the element in the list.

How do you iterate backwards in a list?

We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method. Using IntStream range(int startInclusive, int endExclusive).

Can iterator go backwards?

A reverse iterator is a kind of iterator, that travels in backwards direction. It means when we increment a reverse_iterator, it goes to the previous element in container. So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start.

Can you iterate backwards in Python?

But Python does have a built-in reversed function. If you wrap range() inside reversed() , then you can print the integers in reverse order. range() makes it possible to iterate over a decrementing sequence of numbers, whereas reversed() is generally used to loop over a sequence in reverse order.


2 Answers

The reverse_iterator version shows intent and works across all containers, regardless of their contents.

The first has the deficiency you describe. It also uses >=, which won't work for non-random-access iterators.

The third has the problem that i is an int. It won't be able to hold as much as size() could potentially return. Making it unsigned works (vector<int>::size_type), but then we have the same problem as solution one. (0U - 1 -> Funky terminating checks -> :|)

like image 153
GManNickG Avatar answered Sep 30 '22 18:09

GManNickG


Generally none of the above. Instead, you should usually sit back and relax for a few seconds, figure out which algorithm you want to apply, and forget about writing a loop yourself at all. Chances are that you'll use reverse_iterator with it, but depending on what you're trying to accomplish that won't always be the case (e.g., see std::copy_backwards).

like image 34
Jerry Coffin Avatar answered Sep 30 '22 19:09

Jerry Coffin