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?
The
reverse_iteratorversion 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
iis anint. It won’t be able to hold as much assize()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->:|)