Difference between erase and remove

remove() doesn’t actually delete elements from the container — it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that remove() is designed to work on not just a container but on any arbitrary forward iterator pair: that means it can’t actually delete the elements, because an arbitrary iterator pair doesn’t necessarily have the ability to delete elements.

For example, pointers to the beginning and end of a regular C array are forward iterators and as such can be used with remove():

int foo[100];

...

remove(foo, foo + 100, 42);    // Remove all elements equal to 42

Here it’s obvious that remove() cannot resize the array!

Leave a Comment