How to filter a vector in C++
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {2, 1, 3, 6, 7, 9, 8}; std::vector<int> odd; std::copy_if(v.begin(), v.end(), std::back_inserter(odd), [](int i) { return i % 2 == 1; }); for (int &i: odd) { std::cout << i << ' '; } return 0; } |
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>
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <ranges> int main() { std::vector<int> v = {2, 1, 3, 6, 7, 9, 8}; auto odd = v | std::ranges::views::filter([](int &i) { return i % 2 == 1; }); for (int &i: odd) { std::cout << i << ' '; } return 0; } |
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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {2, 1, 3, 6, 7, 9, 8}; v.erase(std::remove_if(v.begin(), v.end(), [&](const int& i) { return i % 2 == 0; }), v.end()); for (int &i: v) { std::cout << i << ' '; } return 0; } |
Output:
1 3 7 9
That’s all about filtering a vector 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 :)