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,




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


Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.