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.

Download  Run Code

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.

Download  Run Code

Output:

1 3 5 6 7

That’s all about removing all occurrences of an element from a vector in C++.