c++中List在遍历时删除节点的方法,带源码
2012-08-15 19:19
495 查看
今天在开发的过程中遇到问题,想要遍历一个List中的节点,满足一定条件则删除该节点,但是由于使用的是iterator就会出现错误,最后找到解决方法,并写了一个测试程序,呵呵:
// ListTest.cpp : Defines the entry point for the console application.
运行结果:
![](http://my.csdn.net/uploads/201208/15/1345030305_1989.png)
--------------------------------------
@2015-7-20 10:06:01 修正了网友们提到的错误,哈哈,这个错误太低级了,敬请原谅
原来错误的代码:
for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end(); ++iter)
{
if( (*t)->id == 2 )
{
list1.erase(t);
}
}
// ListTest.cpp : Defines the entry point for the console application.
// #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();) { if( (*t)->id == 2 ) { iter = list1.erase(t); } else ++iter; } 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; }
运行结果:
![](http://my.csdn.net/uploads/201208/15/1345030305_1989.png)
--------------------------------------
@2015-7-20 10:06:01 修正了网友们提到的错误,哈哈,这个错误太低级了,敬请原谅
原来错误的代码:
for(list<st_user*>::iterator iter = list1.begin(); iter != list1.end(); ++iter)
{
if( (*t)->id == 2 )
{
list1.erase(t);
}
}
相关文章推荐
- c++下list在遍历时删除节点的方法
- c++中List在遍历时删除节点的方法(转载)
- 遍历Linux kernel的链表时删除节点的方法 list_for_each_safe
- c++ list 遍历删除节点
- 正确遍历删除List中的元素方法(推荐)
- c++实现二叉树的查找,插入,删除,深度,叶子节点数,度为1的节点数(递归方法)及运行实例结果
- C++ map正确的遍历删除方法
- 正确遍历删除List中的元素方法(推荐)
- c++实现二叉树的查找,插入,删除,深度,叶子节点数,度为1的节点数(递归方法)及运行实例结果
- Java集合之List遍历找到匹配元素删除方法总结
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- c++实现二叉树的查找,插入,删除,深度,叶子节点数,度为1的节点数(递归方法)及运行实例结果
- C#遍历List并删除元素的方法概述
- linux中的list源码分析——遍历节点分析
- 174. 删除链表中倒数第n个节点 (remove-nth-node-from-end-of-list)(c++)----lintcode面试题之链表
- c++实现二叉树的查找,插入,删除,深度,叶子节点数,度为1的节点数(递归方法)及运行实例结果
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- C++ set map list的正确删除元素方法
- c++实现二叉树的查找,插入,删除,深度,叶子节点数,度为1的节点数(递归方法)及运行实例结果
- java中循环遍历删除List和Set集合中元素的方法(推荐)