Remove all occurrences of an element from a vector in C++
This post will discuss how to remove all occurrences of an element from a vector in C++.
1. Using Erase-remove idiom
The standard solution to remove values from a range is using the std::remove algorithm. However, std::remove doesn’t have any information of the underlying container and hence does not actually remove elements from the container. It expects a call to the std::erase algorithm. This technique knows as the Erase-remove idiom.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> #include <algorithm> #include <iterator> template<typename T> void remove(std::vector<T> &v, const T &target) { v.erase(std::remove(v.begin(), v.end(), target), v.end()); } int main() { std::vector<int> v = {1, 2, 3, 2, 5, 2, 6, 7}; int target = 2; // remove all occurrences of target remove(v, target); // print the vector std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 3 5 6 7
2. Using std::vector::erase
Another option is to iterate over the vector and remove all the occurrences of the target from the vector using std::vector::erase function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <vector> #include <iterator> template<typename T> void remove(std::vector<T> &v, const T &target) { for (auto it = v.begin(); it != v.end(); it++) { if (*it == target) { v.erase(it); } } } int main() { std::vector<int> v = {1, 2, 3, 2, 5, 2, 6, 7}; int target = 2; // remove all occurrences of target remove(v, target); // print the vector std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 3 5 6 7
That’s all about removing all occurrences of an element from 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 :)