遍历删除测试程序

 /**
 * 遍历删除测试程序
 *
 * 测试遍历stl顺序表类容器的删除操作的正确有效的做法
 *
 * msvc 7.1 编译通过 by lwb
 */
#include "stdafx.h"
#include "conio.h"

#include <vector>
#include <list>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
 typedef list<int> IntList;
 //typedef vector<int> IntList;

 IntList intList;

 intList.push_back(1);
 intList.push_back(2);
 intList.push_back(2);
 intList.push_back(4);
 intList.push_back(2);
 intList.push_back(6);

 // 遍历删除
 IntList::iterator it = intList.begin();  // 放在for循环头中初始也可以
 IntList::iterator end = intList.end();  // 只计算一次结尾位置
 for (;it!=end;)
 {
  // 如果有删除,则it为erase后返回的下一个有效元素位置
  // 如果没有删除,则++it
  if ( *it == 2)
  {
   it = intList.erase(it); // erase 返回下一个有效位置,如果没有则返回end()
  }else
  {
   ++it; // 注意++it比it++更高效些
  }
 }

 printf("==============");

 it = intList.begin();
 end = intList.end();
 for (IntList::iterator t = intList.begin();t!=end;++t)
 {
  printf("/n %d",*t);
 }

 getch();
 
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值