Книга: Standard Template Library Programmer

remove_if

remove_if

Category: algorithms

Component type: function

Prototype

template <class ForwardIterator, class Predicate>
ForwardIterator remove_if(ForwardIterator first, ForwardIterator last, Predicate pred);

Description

Remove_if removes from the range [first, last) every element x such that pred(x) is true. That is, remove_if returns an iterator new_last such that the range [first, new_last) contains no elements for which pred is true. [1] The iterators in the range [new_last, last) are all still dereferenceable, but the elements that they point to are unspecified. Remove_if is stable, meaning that the relative order of elements that are not removed is unchanged.

Definition

Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.

Requirements on types

• ForwardIterator is a model of Forward Iterator.

• ForwardIterator is mutable.

• Predicate is a model of Predicate.

• ForwardIterator's value type is convertible to Predicate's argument type.

Preconditions

• [first, last) is a valid range.

Complexity

Linear. Remove_if performs exactly last – first applications of pred.

Example

Remove all even numbers from a vector.

vector<int> V;
V.push_back(1);
V.push_back(4);
V.push_back(2);
V.push_back(8);
V.push_back(5);
V.push_back(7);
copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
// The output is "1 4 2 8 5 7"
vector<int>::iterator new_end = remove_if(V.begin(), V.end(), compose1(bind2nd(equal_to<int>(), 0), bind2nd( modulus<int>(), 2)));
V.erase(new_end, V.end()); [1]
copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
// The output is "1 5 7".

Notes

[1] The meaning of "removal" is somewhat subtle. Remove_if does not destroy any iterators, and does not change the distance between first and last. (There's no way that it could do anything of the sort.) So, for example, if V is a vector, remove_if(V.begin(), V.end(), pred) does not change V.size(): V will contain just as many elements as it did before. Remove_if returns an iterator that points to the end of the resulting range after elements have been removed from it; it follows that the elements after that iterator are of no interest, and may be discarded. If you are removing elements from a Sequence, you may simply erase them. That is, a reasonable way of removing elements from a Sequence is S.erase(remove_if(S.begin(), S.end(), pred), S.end()).

See also

remove, remove_copy, remove_copy_if, unique, unique_copy.

Оглавление книги

Оглавление статьи/книги

Генерация: 0.027. Запросов К БД/Cache: 0 / 2
поделиться
Вверх Вниз