Based on the list loop to delete elements the problem of iterator failure is explained in detail

  • 2020-05-10 18:33:25
  • OfStack

The point is to save the current iterator before deleting the element. Of course, only list is supported here, because the chain of list removes 1 element, and the previous pointer points to the next element, vector and queue are not easy to handle, they are either linear or semi-linear semi-chain, and the iterator will fail


#include<iostream>
#include<list>
using namespace std;
int main()
{
	list<int *> l;
	for(int i=1;i<=100;i++)
	{


		int* temp=new int;
		*temp=i;
		l.push_back(temp);
	}
	list<int *>::iterator it=l.begin();
	list<int *>::iterator ittemp=l.begin();
	for(;it!=l.end();++it)
	{
		cout<<*(*it)<<endl;


	}
	it=l.begin();
	ittemp=l.begin();
	for(;it!=l.end();)
	{
		ittemp=it;
		++it;
		delete (*ittemp);
		l.erase(ittemp);


	}
	cout<<l.size()<<endl;
	return 0;


}

Related articles: