/**
* 遍历删除测试程序
*
* 测试遍历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;
}