I want to process elements from a vector for some time. To optimize this I don’t want to remove an item when it is processed and I remove all processed items at the end.
vector<Item*>::iterator it;
for(it = items.begin(); it != items.end(); ++it)
{
DoSomething(*it);
if(TimeIsUp())
{
break;
}
}
items.erase(items.begin(), it);
Is it safe to use erase when it == items.end()? In documentaion it is said that erase() will erase [first,last) and this should be safe but I want to be sure.
EDIT:
Is it safe to use std::vector.erase(begin(), begin())?
What that
[first,last)means is everything betweenfirstandlast, includingfirstbut not includinglast. It denotes a half-open set. Had they used[first,last],lastwould also be included; had they they used(first,last),firstandlastwould be excluded.There is a problem with your code. You want the element at
itto be deleted ifitisn’t equal toend(). Instead ofitems.erase (items.begin(),it), you should be using