This post will discuss how to erase elements from a vector in C++.

Sometimes, we may want to erase one or more elements from a vector based on some criteria, such as the index, the value, or a condition. For example, we may want to erase the first element, the last element, or all the elements from a vector. Or we may want to erase all the elements that are equal to a given value, present at given index, or that satisfy a given predicate.

1. Using std::erase function

One way to erase elements from a vector in C++ is to use the erase() function from the std::vector class. This function removes an element or a range of elements from a vector, and returns an iterator pointing to the element following the last removed element. The erase() function also shifts the remaining elements to fill the gap left by the removed elements, and reduces the size of the vector accordingly.

To use the erase() function to erase elements from a vector, we need to provide an iterator that specifies which element to remove. Since calling the erase() function invalidates the iterator, we should use its return value for setting the iterator to the next element. For example:

Download  Run Code

 
We can also use iterators to erase a range of elements from a vector. For example, if we want to erase all the elements except the first and the last ones from a vector, we can do something like this:

Download  Run Code

2. Using std::remove_if or std::remove function

Another way to erase elements from a vector in C++ is to use the std::remove_if algorithm from the <algorithm> header. It removes all the elements that satisfy a given predicate from a range, and return an iterator pointing to the new end of the range. To use the std::remove_if algorithm to erase elements from a vector, we need to provide three or four arguments: the beginning and the end of the range (the vector), the predicate to satisfy, and optionally an output iterator that specifies where to store the removed elements. For example, if we want to erase all the elements that are equal to 2 from a vector, we can do something like this:

Download  Run Code

 
Note that the std::remove_if algorithm do not actually erase the elements from the vector, but rather move them to the end of the range and leave them there. Therefore, we need to use the erase() function after calling the std::remove_if algorithm to actually erase the elements from the vector. We can also use the std::remove algorithm, which remove all the elements that are equal to a given value:

Download  Run Code

That’s all about erasing elements from a vector in C++.