Name

remove function template — Reorders a range to remove all occurrences of a value

Synopsis

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.

Note

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.

Technical Notes

The remove function template assigns *(first + n++) = *(first + m), in which n starts at 0, for all values of m in [0, last - first) in which *(first + m) == value is false. The return value is first + n.

Complexity is ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.