Erase-remove idiom
Encyclopedia
The erase-remove idiom is a common C++
technique to eliminate elements that fulfill a certain criterion from a C++ Standard Library
container.
. 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".
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 collectionCollection (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".