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

In this article we will see how to erase elements from a std::list using iterators.

std::list provides 2 member function to delete elements using iterators i.e.

iterator erase (const_iterator position);

It deletes the element representing¬†by passed iterator¬†“position” and returns the iterator of element next to last deleted element.
iterator erase (const_iterator first, const_iterator last);

It accepts a range of elements as an argument and deletes all the elements in range (firs, last] and returns the iterator of element next to last deleted element.
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>

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

	//Display The List
	std::copy(listOfInts.begin(), listOfInts.end(),
			std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	// Iterator itList points to element next to begin
	std::list<int>::iterator itList = ++(listOfInts.begin());

	// Erasing element represented by iterator itList i.e. 3
	itList = listOfInts.erase(itList);

	//Display The List
	std::copy(listOfInts.begin(), listOfInts.end(),
			std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	//Increment iterator
	itList++;

	// Erase a range of elements i.e. 6 to end
	listOfInts.erase(itList, listOfInts.end());

	//Display The List
	std::copy(listOfInts.begin(), listOfInts.end(),
			std::ostream_iterator<int>(std::cout, " "));
	std::cout << std::endl;

	return 0;
}

Output
2 3 4 6 4 9 1 2 8 9 4 6 2 4 9 
2 4 6 4 9 1 2 8 9 4 6 2 4 9 
2 4

 

To compile above code on Linux use following command,

g++ –std=c++11 example.cpp

Advertisements

 

[showads ad=inside_post]

 

In the next articles we will see how to erase elements using a criteria and also in a loop.

Thanks

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.

1 thought on “How to erase elements from a list in c++ using iterators”

  1. Pingback: How to remove elements from a List while Iterating – thisPointer.com

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