STL列表,删除所有奇数 [英] STL list, delete all the odd numbers

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

问题描述

我试图学习如何使用STL,并试图写一个函数,它将接收到一个列表,并将尝试删除所有奇数成员。
我的代码有一个小问题。这是我的代码

I am trying to learn how to work with STL and tried to write a function which will recieve a refference to a list and will try to delete all odd members. I am having a slight problem in my code.Here is my code

void removeOdds(list<int>& myvector)
{
    for(list<int>::iterator p=myvector.begin(); p !=myvector.end();p++)
    {
        if(*p%2 !=0)
        {
            list<int>::iterator temp=myvector.erase(p);
            p=temp;
            if(p !=myvector.begin())
                p--;
        }
    }
}

如果我通过一个包含1 3 5 2 6 7的列表。删除1后,它显然跳到5,而不是3.
我如何解决这个问题,因为p ++递增,p不发生,因为我在开始。

The problem that I am having is that If I pass a list containing 1 3 5 2 6 7 for example. After deleting 1, it obviously skips to 5, and does not look at 3. How can I fix this, because that p++ increments, and p-- does not happen because I am at the beginning.

推荐答案

最简单的方法是使用 std :: list :: remove_if 。这将从列表中删除基于一元谓词的元素。例如,

The easiest way to do it would be to use std::list::remove_if. This removes elements from the list based on a unary predicate. For example,

myvector.remove_if([](int n) { return n % 2 != 0; });

使用STL * 的最佳方式是知道

The best way to work with the "STL"* is to know what is in it.

对于前C ++ 11实现(例如实际的STL),您可以传递一个函数:

For pre-C++11 implementations (such as the actual STL), you can pass a function:

bool is_odd(int n) { return n % 2 != 0; }

myvector.remove_if(is_odd);






*STL但这也适用于C ++标准库

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

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