Iterating backward
- by MBennett
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?