如何从列表中删除奇数位置? [英] How to remove odd positions from a list?

查看:154
本文介绍了如何从列表中删除奇数位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

void compute(int num)
{
list<int> L;
list<int>::iterator i;
list<int>::iterator i2;
int p;
cout<<"Enter the number of numbers\n";
cin>>p;
int a;
for(int k=1;k<=p;k++)
{
    cin>>a;
    L.push_back(k);
}
cout<<endl;
for(i=L.begin() ; i!=L.end() ; ++i)
{
    cout<<*i<<endl;
}

long int k=1;

for(i=L.begin() ; i!=L.end() ; ++i )
{
    if(k%2!=0) //This is where I try and delete values in odd positions
    {
        i2=L.erase(i);
    }
    k++;
}

for(i=L.begin() ; i!=L.end() ; ++i )
{
    cout<<*i<<endl;
}

}

int main()
{
//  int testcases, sailors;
//cin>>testcases;

//for(int i=1 ; i<=testcases ; i++)
{
//  cin>>sailors;
}
//for(int i=1;i<=testcases;i++)
{
//  int num;
    //cin>>num;
    //compute(num);
}
compute(0);
return 0;

}

我正在尝试使用列表中的L.erase()函数擦除元素.但我说错了 调试断言失败!……Expression:列表迭代器不可递增" 但是我们可以增加迭代器,对吗?

I am trying to erase elements using L.erase() function in Lists. But I get an error saying "Debug assertion failed! ......Expression:list iterator not incrementable" but we CAN increment iterator right?

推荐答案

erase会使作为参数传入的迭代器无效-因为只是删除了迭代器指向的位置上的元素!在同一个迭代器上,尝试在代码中的下一个for循环中进行递增!这就是为什么它会失败.

erase invalidates the iterator that was passed in as parameter - since the element at the position the iterator was pointing to was just erased! And on that same iterator, an increment is attempted in the next for loop in your code! That's why it fails.

但是,擦除它会返回一个指向新位置的迭代器,我们可以使用它;因此,从STL容器中擦除内容的循环应类似于以下内容;我以您使用的类型,列表来显示它,但是您也可以使用例如向量:

However, erase it will return an iterator pointing to the new position, which we can use; a loop where you erase something from an STL container should therefore look something like the following; I show it with the type you use, list, but you could just as well use e.g. vector:

list<int> L;
// ...
list<int>::iterator it=L.begin();
while (it!=L.end())
{
    if(eraseCondition)
    {
        it=L.erase(it);
    }
    else
    {
        ++it;
    }
}

或者,如果可能的话,最好使用 std::remove_if :

Or, if possible, it's even better to use std::remove_if:

container.erase(std::remove_if(L.begin(), L.end(), predicate), L.end());

在您的情况下,由于predicate需要状态信息(索引是奇数还是偶数的信息),因此很难使用(即使不是不可能).因此,我建议您使用上述的循环结构;只需记住remove_if即可删除某个谓词返回true的所有元素的一般情况!

In your case that will be hard - if not impossible - to use since the predicate would need state information (the information whether the index is odd or even). So I'd recommend going with a loop structure as mentioned above; just keep in mind the remove_if for the general case of removing all elements where a certain predicate returns true!

这篇关于如何从列表中删除奇数位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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