I tried to iterate a vector and delete item if certain condition met. Is this an efficient implementation?
Any comments?
Thanks for the help
Chris
Iterator it = myVector.end();
-- it;
while( it != myVector.begin())
{
//remove the item if the condition met
if( it->condition )
{
Iterator itTemp = it - 1;
myVecoter.erase(it);
it = itTemp;
}
else
-- it;
Each vector::erase() copies all elements from the one that's being deleted to the end of the vector. Given an n-element vector, this is O(n) copies. Given m elements to delete, your algorithm performs O(m*n) copies.
The standard std::remove_if() followed by a single vector::erase() is linear
If it->condition doesn't depend on the order of iteration, the efficient solution is simply