This post will discuss how to remove elements from a vector that fulfill a predicate in C++.

1. Using Erase-remove idiom

The standard solution to conditionally remove elements from a vector in C++ is using the Erase-remove idiom technique. The name goes after the erase() and remove() functions, since std::remove does not actually remove elements from the underlying container but expects a call to the std::vector::erase algorithm to actually remove elements. For example,

Download  Run Code

Output:

1 3 5

2. Using std::erase_if

Starting with C++20, we can use the std::erase_if algorithm that erases all elements from the vector satisfying the supplied predicate. It is defined in header <vector> and simplifies the Erase-remove idiom.

Download Code

Output:

1 3 5

That’s all about removing elements from a vector that fulfill a predicate in C++.