I need to erase all elements from a vector which fulfill a certain criteria.
My first approach would be to loop through the vector and call vector::erase on all elements which fulfill the criteria.
As far as I understand, vector::erase
has a bad performance for this use case, because it removes the item from the underlying array, and moves the rest of the vector forward by one element (or more if you erase a range of elements).
When you remove multiple elements, the rear elements will be shifted at each removal.
The remove
algorithm takes all the elements to be removed, and moves them to the end of the vector, so you only have to remove that rear part of the vector, which involves no shifting.
But why is this faster than erasing? (is it even faster?)
Doesn't moving an element to the end imply moving all the following elements forward like in vector::erase
?
How comes, that remove only has a complexity of O(n)?
remove / erase
should be used. – Intercession