Remove elements from a container
This sample is licensed under the CC0 Public Domain Dedication.
Use the erase-remove idiom to remove elements from a container.
algorithms do not have knowledge about the underlying storage of
the given range, so cannot actually remove elements from that
storage. Instead, these algorithms actually shift (by means of move
assignment) the elements in the range in such a way that the
elements not removed form a new range at the beginning of the
original range. The algorithms return a past-the-end iterator for
this new range, which, since the removed elements have been shifted
to the end of the original range, also marks the start of the
On lines 8–9, we show how we can pass the resulting iterator to the
erase member function,
which actually removes the elements from the container. Similarly,
on lines 11–13, we demonstrate how
std::remove_if can be used with
erase to remove all elements for which a given predicate returns
true (in the sample, we remove all even elements).
This technique of using the generic remove algorithms followed by
a call to the particular container’s
erase member function is
commonly referred to as the erase-remove idiom.