I recently learned about the right way to work with reverse iterators in C++ (specifically when you need to erase one). (See this question and this one.)
This is how you're supposed to do it:
typedef std::vector<int> IV;
for (IV::reverse_iterator rit = iv.rbegin(), rend = iv.rend();
rit != rend; ++rit)
{
// Use 'rit' if a reverse_iterator is good enough, e.g.,
*rit += 10;
// Use (rit + 1).base() if you need a regular iterator e.g.,
iv.erase((rit + 1).base());
}
But I think this is much better:
for (IV::iterator it = iv.end(), begin = iv.begin();
it-- != begin; )
{
// Use 'it' for anything you want
*it += 10;
iv.erase(it);
}
Pros:
- Uses a familiar idiom for reverse for-loops
- Don't have to remember (or explain) the
+1
- Less typing
- Works for std::list too:
it = il.erase(it);
- If you erase an element, you don't have to adjust the iterator
- If you erase, you don't have to recompute the begin iterator
Cons:
- You tell me. What's wrong with it?