我想在迭代时从列表中删除项目.我以前做过这个,但不知怎的,这个简单的例子让我失望了.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();
}
Run Code Online (Sandbox Code Playgroud)
只是FWIW,您所谈论的内容也可以完成(例如)std::list::remove_if:
template <class T>
class odd {
bool operator()(T const &value) {
return value % 2 != 0;
}
};
// ...
x.remove_if(odd);
Run Code Online (Sandbox Code Playgroud)
使用C++ 0x和/或Boost lambda,您可以在不even单独定义的情况下执行此操作,这对于像这样的琐碎条件非常方便.理论上你也可以用std :: bind1st,std :: bind2nd,std :: equal和std :: modulus的组合来定义它,但是(IMO)结果将很难破译它会是不宜.
请注意std::list::remove_if(不像std::remove_if)实际上会删除您要求删除的项目,而std::remove_if通常需要与调用相结合erase才能实际删除已删除的项目.
erase在删除元素后返回元素:http://www.cplusplus.com/reference/stl/vector/erase/
所以尝试这样的事情:
for( list<int>::iterator k = x.begin(); k != x.end();)
if( (*k)%2 )
k=x.erase(k);
else
++k;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1375 次 |
| 最近记录: |