Codectionary / Developer documentation / C++

C++ erase–remove filtering

The erase–remove idiom filters a vector in two stages: remove_if moves retained elements to the front, and erase shrinks the container. This example works in C++11 and later.

Syntax

items.erase(std::remove_if(items.begin(), items.end(), predicate), items.end());

Examples

C++ erase–remove filtering

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <algorithm>
#include <vector>
#include <iostream>
int main() {
    std::vector<int> scores{4, -1, 7, -3};
    scores.erase(std::remove_if(scores.begin(), scores.end(),
        [](int score) { return score < 0; }), scores.end());
    for (int score : scores) std::cout << score << ' ';
    std::cout << '\n';
}
  1. Output values: 4 7. remove_if alone would leave the vector size unchanged.

Best practices

  • Do not inspect the removed tail as meaningful data. Reacquire invalidated iterators after erasure; C++20 also offers std::erase_if.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading