c++中List在遍历时删除节点的方法(转载)

原文地址:http://blog.csdn.net/sonikk/article/details/7870490

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


//

#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(); )
	{
		
		list  ::iterator t = iter++; 

		if( (*t)->id == 2 )
		{
			list1.erase(t);
		}

	}


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


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


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


	system("pause");


	return 0;
}

运行结果:



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