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?
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.
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).
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.
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.
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
-> :|
)
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With