This post will discuss how to filter a vector in C++.

1. Using std::copy_if

Starting with C++11, we can filter a vector using the std::copy_if algorithm. It copies all the elements in the specified range for which the predicate returns true. Following is a simple example demonstrating the usage of this function, which filters odd elements from the vector.

Download  Run Code

Output:

1 3 7 9

2. Using Ranges

Starting with C++20, we can use filter view from the ranges library. Here is a simple one-liner C++20 solution with std::ranges::views::filter from header <ranges>.

Download Code

Output:

1 3 7 9

3. Using Erase-remove idiom

We can in-place filter a vector with Erase-remove idiom, as shown below using the std::remove_if with a single call to std::vector::erase.

Download  Run Code

Output:

1 3 7 9

That’s all about filtering a vector in C++.