首页 > 代码库 > STL在迭代的过程中,删除指定的元素

STL在迭代的过程中,删除指定的元素

直接上Code,上 Picture

#include <iostream>
#include <list>

using namespace std;

// STL在迭代的过程中,删除指定的元素
int main()
{
	list<int> listTest;

	listTest.push_back(-1);
	listTest.push_back(-1);
	listTest.push_back(-1);
	listTest.push_back(-1);

	cout<<"list size: "<<listTest.size()<<endl;

	list<int>::iterator itList;

	for (itList=listTest.begin(); itList != listTest.end(); /*no itList++ !!*/ )
	{
		cout<<"data: "<<*itList<<endl;

		// 第一种方法
		if (*itList <= 0)
			itList = listTest.erase(itList);
		else
			++itList;
	}
	cout<<"list size: "<<listTest.size()<<endl;
	cout<<"======================================"<<endl;


	listTest.push_back(-1);
	listTest.push_back(-1);
	listTest.push_back(-1);
	listTest.push_back(1);

	cout<<"list size: "<<listTest.size()<<endl;
	
	for (itList=listTest.begin(); itList != listTest.end(); ++itList)
	{
		cout<<"data: "<<*itList<<endl;

		// 第二种方法
		if (*itList <= 0)
			*itList = 0;		// 做个记录标志,等待迭代完进行回收
	}

	listTest.remove(0);			// 回收 0

	cout<<"list size: "<<listTest.size()<<endl;
	cout<<"======================================"<<endl;

	return 0;

}

运行结果: