Filter STL containers (vector, set, list, etc) in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <set> #include <algorithm> int main() { std::set<int> s = { -1, 4, -5, 8, 0, 6 }; std::set<int> positive; // filter positive numbers std::copy_if(s.begin(), s.end(), std::inserter(positive, positive.end()), [](int i) { return i > 0; }); for (const auto &val: positive) { std::cout << val << ' '; } return 0; } |
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>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <set> #include <ranges> int main() { std::set<int> s = { -1, 4, -5, 8, 0, 6 }; // filter positive numbers using std::ranges::views::filter; auto positive = s | filter([](int i) { return i > 0; }); for (const auto &val: positive) { std::cout << val << ' '; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <set> #include <boost/range/adaptors.hpp> int main() { std::set<int> s = { -1, 4, -5, 8, 0, 6 }; // filter positive numbers using boost::adaptors::filtered; auto positive = s | filtered([](int i) { return i > 0; }); for (const auto &val: positive) { std::cout << val << ' '; } return 0; } |
Output:
4 6 8
That’s all about filtering STL containers (vector, set, list, etc.) in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)