How to remove elements from a List while Iterating

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,

#include <iostream>
#include <list>
#include <algorithm>

int main() {
	// Create a list and initialize it with 10 elements
	std::list<int> listOfInts( { 2, 3, 3, 4, 8, 9, 4, 6, 8, 3 });

	// Iterate over the list using Iterators and erase elements
	// which are multiple of 3 while iterating through list
	std::list<int>::iterator it = listOfInts.begin();
	while (it != listOfInts.end()) {
		// Remove elements while iterating
		if ((*it) % 3 == 0) {
			// erase() makes the passed iterator invalid
			// But returns the iterator to the next of deleted element
			it = listOfInts.erase(it);
		} else

	// Iterate over the list using for_each & Lambda Function and display contents
	std::for_each(listOfInts.begin(), listOfInts.end(), [](const int & val) {
	std::cout << std::endl;

	return 0;



[showads ad=inside_post]



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


Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top