Skip to content
C++ Basics: Remove Matching Vector Elements with erase_if

C++ Basics: Remove Matching Vector Elements with erase_if

November 2, 2026

Filtering a vector requires both moving retained values and reducing its size. C++20 std::erase_if performs those steps together.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and its standard-library headers, and make g++ available on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as vector-erase-if-demo.cpp:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> measurements{5, -1, 8, -3, 0};
    const auto removed = std::erase_if(measurements, [](int measurement) {
        return measurement < 0;
    });
    std::cout << "Removed: " << removed << '\n';
    std::cout << "Remaining:";
    for (const int measurement : measurements) {
        std::cout << ' ' << measurement;
    }
    std::cout << "\nSize: " << measurements.size() << '\n';
}

Compile and run it. The && prevents execution if compilation fails:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic vector-erase-if-demo.cpp -o vector-erase-if-demo &&
./vector-erase-if-demo

Observed output:

Removed: 2
Remaining: 5 8 0
Size: 3

Read the result

The predicate selects negative readings for removal. Two values disappear, the remaining values retain their relative order, and size() becomes three. The return value directly reports the number removed.

Apply it carefully

std::erase_if for vector is available from C++20. Before C++20, the erase-remove idiom combines remove_if with a range erase; remove_if alone does not shorten the vector. Treat old iterators and references at or after the changed region as invalid. Keep the predicate free of modifications to the container being filtered.

The C++ working draft documents the relevant container behavior. The example uses only features available in C++20, even though the linked draft may include later additions.

Clean up

Remove only the source and executable created here, then remove the empty practice directory:

rm -- vector-erase-if-demo.cpp vector-erase-if-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on