This post will discuss how to filter STL containers (vector, set, list, etc.) in C++.

1. Using std::copy_if

A simple solution is to use the std::copy_if standard algorithm that takes a predicate to do the filtering. It copies the elements in the specified range to the destination range for which the specified predicate returns true. The >std::copy_if algorithm is introduced with C++11, and can be used as follows:

Download  Run Code

Output:

4 6 8

2. Using Ranges Library

In C++20, we can use filter view from the ranges library. Here’s a simple one-liner that lazily returns all the positive elements in a set container using std::ranges::views::filter from header <ranges>.

Download Code

Output:

4 6 8

3. Using Boost Library

Before C++20, you can use Boost.Range which provides adaptors returning a new range based on another range. For example, the following code uses boost::adaptors::filter() to remove all numbers from the specified range that aren’t positive. The boost::adaptors::filter() function takes a range to filter and a predicate, as the first and second parameters, respectively.

Download Code

Output:

4 6 8

That’s all about filtering STL containers (vector, set, list, etc.) in C++.