remove function template — Reorders a range to remove all occurrences of a value
template<typename FwdIter, typename T>
FwdIter remove(FwdIter first, FwdIter last, const T& value);
The remove
function
template "removes" items that are equal to value
from the range [first
, last
). Nothing is actually erased from the
range; instead, items to the right are copied to new positions so
they overwrite the elements that are equal to value
. The return value is one past the
new end of the range. The relative order of items that are not
removed is stable.
The only way to erase an element from a container is to call
one of the container's member functions. Therefore, the remove
function template does not and
cannot erase items. All it can do is move items within its given
range. A typical pattern, therefore, is to call remove
to reorder the container's
elements, and then call erase
to erase the unwanted elements. To help you, the value returned
from remove
is an iterator that
points to the start of the range that will be erased. For
example:
std::vector<int> data ... // Erase all values that are equal to 42. std::erase(std::remove(data.begin( ), data.end( ), 42), data.end( ));
See Figure 13-13
(under remove_copy
) for an
example of the removal process.