STL remove doesn’t work as expected?

Actually std::remove doesn’t remove the item from the container. Quoted from here

Remove removes from the range [first, last) all elements that are equal to value. That is, remove returns an iterator new_last such that the range [first, new_last) contains no elements equal to value. The iterators in the range [new_last, last) are all still dereferenceable, but the elements that they point to are unspecified. Remove is stable, meaning that the relative order of elements that are not equal to value is unchanged.`

That is, std::remove works with a pair of iterators only and does not know anything about the container which actually contains the items. In fact, it’s not possible for std::remove to know the underlying container, because there is no way it can go from a pair of iterators to discover about the container to which the iterators belong. So std::remove doesn’t really remove the items, simply because it cannot. The only way to actually remove an item from a container is to invoke a member function on that container.

So if you want to remove the items, then use Erase-Remove Idiom:

 v.erase(std::remove(v.begin(), v.end(), 10), v.end()); 

The erase-remove idiom is so common and useful is that std::list has added another member function called list::remove which produces the same effect as that of the erase-remove idiom.

 std::list<int> l;
 //...
 l.remove(10); //it "actually" removes all elements with value 10!

That means, you don’t need to use erase-remove idiom when you work with std::list. You can directly call its member function list::remove.

Leave a Comment