This post will discuss how to remove elements from a vector while iterating inside a loop in C++.

The idea is to use iterators to iterate the vector and call the vector::erase function if the current element matches the predicate. Since calling the erase() function on the vector element invalidates the iterator, special care needs to be taken while erasing an element. We can do that in many ways:

 
1. Use the return value of erase() for setting the iterator to the next element.

Download  Run Code

Output:

2 4 6

 
2. Decrement the iterator after it is passed to the erase() but before erase() is executed.

Download  Run Code

Output:

2 4 6

 
3. Call erase() on a duplicate of the original iterator after advancing the original iterator to the next element.

Download  Run Code

Output:

2 4 6

 
Another solution is to use the std::remove_if with vector::erase, as shown below. This solution is valid as std::remove_if uses the loop behind the scenes.

Notice that the std::remove_if algorithm has no knowledge of the underlying container. It does not actually remove elements from the container but move all safe elements to the front and returns an iterator pointing to where the end should be, so they can be deleted using a single call to std::erase. This technique is commonly known as the Erase-remove idiom.

Download  Run Code

Output:

2 4 6

That’s all about removing elements from a vector inside a loop in C++.