remove_if

Syntax:

    #include <algorithm>
    forward_iterator remove_if( forward_iterator start, forward_iterator end, Predicate p );

The remove_if() function removes all elements in the range [start,end) for which the predicate p returns true.

The return value of this function is an iterator to the last element of the pruned range.

Note that remove_if() doesn't actually “remove” things from the range [start, end); if remove_if() is called on a container, the length of the container will remain the same afterwards (remove_if() couldn't possibly affect that through the iterators alone), and all the elements will still be in the container. Instead, remove_if() puts all the “not-removed” elements to the start of the container, and returns the iterator that separates the not-removed and the rest. Note that everything after the returned iterator is still present. To actually remove items from a container, you would have to call the erase() method of the container, to erase elements starting at the returned iterator. This is usually combined in what is called the erase-remove idiom:

container.erase(remove_if(container.begin(), container.end(), pred), container.end());

remove_if() is similar to partition() except two differences: 1) The predicate is reversed. 2) Only the first half of the partition is extracted (the second partition is left untouched)

remove_if() runs in linear time.

remove_if() cannot be used with associative containers like set<> or map<>.

Related Topics: remove, remove_copy, remove_copy_if