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

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

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


//

#include "stdafx.h"

#include <iostream>
#include <list>
#include <algorithm>
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<st_user*> list1;

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


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


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


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


	for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end(); )
	{
		
		list <st_user*> ::iterator t = iter++; 

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

	}


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


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


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


	system("pause");


	return 0;
}

运行结果:



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值