Remove elements from a vector that fulfill a predicate in C++
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,
|
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> #include <iterator> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; // delete even elements from the vector v.erase(std::remove_if(v.begin(), v.end(), [](const int& x) { return x % 2 == 0; }), v.end()); // print vector contents to std::cout std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; // delete even elements from the vector std::erase_if(v, [](const int& x){ return x % 2 == 0; }); // print vector contents to std::cout std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 3 5
That’s all about removing elements from a vector that fulfill a predicate 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 :)