c++中List在遍历时删除节点的方法,带源码

今天在开发的过程中遇到问题,想要遍历一个List中的节点,满足一定条件则删除该节点,但是由于使用的是iterator就会出现错误,最后找到解决方法,并写了一个测试程序,呵呵:



// ListTest.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include 
#include 
#include 
using namespace std;


struct st_user
{
	int id;
	char name[255];
};

int _tmain(int argc, _TCHAR* argv[])
{

	st_user a1,a2,a3;

	a1.id = 1;
	sprintf(a1.name,"%s","xxxxxxxxx");
	a2.id = 2;
	sprintf(a2.name,"%s","fff");
	a3.id = 3;
	sprintf(a3.name,"%s","bbbb");

	list list1;

	list1.push_back(&a1);
	list1.push_back(&a2);
	list1.push_back(&a3);


	printf("------------------------------\n");


	for(list::iterator iter = list1.begin(); iter != list1.end(); ++iter)
	{
		printf("%s \n", (*iter)->name);
	}


	printf("------------------------------\n");


	for(list::iterator iter = list1.begin(); iter != list1.end();)
	{
		if( (*t)->id == 2 )
		{
			iter = list1.erase(t);
		}
		else
			++iter;

	}

	printf("------------------------------\n");


	for(list::iterator iter = list1.begin(); iter != list1.end(); ++iter)
	{
		printf("%s \n", (*iter)->name);
	}


	printf("------------------------------\n");


	system("pause");


	return 0;
}



运行结果:



--------------------------------------

@2015-7-20 10:06:01 修正了网友们提到的错误,哈哈,这个错误太低级了,敬请原谅

原来错误的代码:

	for(list::iterator iter = list1.begin(); iter != list1.end(); ++iter)
	{
		if( (*t)->id == 2 )
		{
			list1.erase(t);
		}
	}


 
  

你可能感兴趣的:(c++)