We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

83
5.205.358,90

Cart

Quantity 2.500,00
Quantity 3.500,00
Quantity 116,00
Quantity 3.000,00
Quantity 1.300,00
Quantity 3.500,00
Quantity 50,00
Quantity 1.600,00
Quantity 11.934,00
Quantity 9.500,00
Quantity 35,00
Quantity 5.700,00

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

83
5.205.358,90

Cart

Quantity 2.500,00
Quantity 3.500,00
Quantity 116,00
Quantity 3.000,00
Quantity 1.300,00
Quantity 3.500,00
Quantity 50,00
Quantity 1.600,00
Quantity 11.934,00
Quantity 9.500,00
Quantity 35,00
Quantity 5.700,00