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
			it++;
	}

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

	return 0;
}

 Output:
2,4,8,4,8,

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

 

Join a list of 2000+ Programmers for latest Tips & Tutorials