Iterating backward

Posted by MBennett on Stack Overflow See other posts from Stack Overflow or by MBennett
Published on 2010-03-30T21:33:22Z Indexed on 2010/03/30 21:43 UTC
Read the original article Hit count: 339

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about iterators