【发布时间】:2011-04-21 11:11:22
【问题描述】:
可能重复:
Can you remove elements from a std::list while iterating through it?
我想在迭代时从列表中删除项目。我以前做过,但不知何故这个简单的例子让我失望了。 thnx 提前寻求帮助!
#include<iostream>
#include<list>
using namespace std;
void main()
{
list<int> x;
for ( int i =0;i<10; i++)
x.push_back(i);
for( list<int>::iterator k = x.begin(); k != x.end();k++)
cout<<*k<<" ";
cout<<endl;
for( list<int>::iterator k = x.begin(); k != x.end();k++)
{
if ((*k)%2)
{
x.erase(k);
}
}
cout<<endl;
getchar();
}
【问题讨论】: