In this article we will see how to delete an element from a list while iterating through it.

Removing Elements From a List while Iterating through it

std::list provides a member function erase() that accepts an iterator and deletes the element pointed by that Iterator. But it makes that iterator invalid i.e. we cannot use that iterator because that is already deleted and all its links has become invalid.

Therefore, std::list::erase() returns the iterator to the next of last deleted element. So, we can use this to continue our iteration. Lets see how to delete all the elements from a list that are multiple of 3, while iterating through the list,

 Output:

Thanks.

 

To know more about other ways to delete elements from a list checkout following articles,

How to remove elements from a List based on value or Criterion

How to erase elements from a list in c++ using iterators