Erase-remove idiom
Encyclopedia
The erase-remove idiom is a common C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 technique to eliminate elements that fulfill a certain criterion from a C++ Standard Library
C++ standard library
In C++, the C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself...

 container.

Motivation

A common programming task is remove all elements that have a certain value or fulfill a certain criterion from a collection
Collection (computing)
In computer science, a collection is a grouping of some variable number of data items that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion. Generally, the data items will be of the same type or, in languages supporting...

. In C++, this could be achieved using a hand-written loop. It is, however, preferred to use an algorithm from the C++ Standard Library for such tasks.

The algorithm library provides the remove and remove_if algorithms for this. Because these algorithms operate on a range of elements denoted by two forward iterators, they have no knowledge of the underlying container or collection. Thus, the elements are not actually removed from the range, merely moved to the end. When all the removed elements are at the end of the range, remove returns an iterator pointing one past the last unremoved element.

To actually eliminate elements from the container, remove is combined with the container's erase member function, hence the name "erase-remove idiom".

Example

  1. include // the general-purpose vector container
  2. include // remove and remove_if


bool is_odd(int i) { // unary predicate returning true if and only if the argument is odd
return i % 2;
}
bool is_even(int i) { // unary predicate returning true if and only if the argument is even
return !is_odd(i);
}

int main {
using namespace std;
int elements[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// create a vector that holds the numbers from 0-9.
vector v(elements, elements + 10);

// use the erase-remove idiom to remove all elements with the value 5
v.erase(remove(v.begin, v.end, 5), v.end);

// use the erase-remove idiom to remove all odd numbers
v.erase( remove_if(v.begin, v.end, is_odd), v.end );

// use the erase-remove idiom to remove all even numbers
v.erase( remove_if(v.begin, v.end, is_even), v.end );
}
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK