We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

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.

Advertisements

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

 

[showads ad=inside_post]

 

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

Thanks

Cart

Your Cart is Empty

Back To Shop