STL列表擦除项目 [英] STL list erase items

查看:94
本文介绍了STL列表擦除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我要在迭代时从列表中删除项目。我以前做过,但不知何故这个简单的例子失败了我。 thnx提前帮助!

I want to erase items from the list while iterating over. I have done this before, but somehow this simple example fails me. thnx for the help in advance!

#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();
}


推荐答案

erase 返回已删除元素之后的元素: http:// www.cplusplus.com/reference/stl/vector/erase/

erase returns the element after the erased element: 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;

这篇关于STL列表擦除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆