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

The idea is to iterate the list using iterators and call list::erase on the desired elements. But we can’t directly call the erase() function inside a for-loop since calling it invalidates the iterator. We can handle this in many ways:

 
1. We can reset the iterator to the next element in the sequence using the return value of erase(). Note that this will only work with C++11 and above.

Download  Run Code

Output:

red
blue
gray

 
2. We can also decrement the iterator inside the function arguments using the postfix decrement operator. This way, a copy of the iterator is passed to the erase() function, and the actual iterator is incremented.

Download  Run Code

Output:

red
blue
gray

 
3. Like the second solution, we can call the erase() function on a copy of the original iterator after advancing the original iterator to the next element.

Download  Run Code

Output:

red
blue
gray

That’s all about removing elements from a list while iterating through it in C++.