【问题标题】:Turning remove_if into remove_not_if将 remove_if 变成 remove_not_if
【发布时间】:2010-10-05 14:27:26
【问题描述】:

如何反转谓词的返回值,并删除返回 false 而不是 true 的元素?

这是我的代码:

headerList.remove_if(FindName(name));

(请忽略缺少擦除)

使用 FindName 是一个简单的函子:

struct FindName
{
    CString m_NameToFind;

    FindInspectionNames(const CString &nameToFind)
    {
        m_NameToFind = nameToFind;
    }

    bool operator()(const CHeader &header)
    {
        if(header.Name == m_NameToFind)
        {
            return true;
        }

        return false;
    }
};

我想要类似的东西:

list.remove_if(FindName(name) == false);

还没有使用 c++0x,所以很遗憾,不允许使用 lambda。我希望有比编写 NotFindName 函子更好的解决方案。

【问题讨论】:

    标签: c++ stl predicates remove-if


    【解决方案1】:

    <functional> 标头中检查not1

    headerList.remove_if( std::not1( FindName( name ) ) );
    

    哦,还有这个:

    if(header.Name == m_NameToFind)
    {
        return true;
    }
    
    return false;
    

    不要那样做。

    return ( header.Name == m_NameToFind );
    

    这样好多了,不是吗?

    【讨论】:

    • 谢谢,它适用于以下模组: Functor 需要继承自 std::unary_function operator() 需要是 const 成员函数
    • 其实继承不是必须的,但是你需要定义合适的typedef,它免费提供给你。至于const-ness,那就不用说了:)
    【解决方案2】:

    或者,您可以使用 boost bind,这样您就不必编写该 unary_function 结构:

    bool header_has_name (const CHeader& h, const CString& n) {return h.name == n;}
    
    headerList.remove_if (boost::bind (header_has_name, _1, "name"));
    

    对于 remove_if_not:

    headerList.remove_if (!boost::bind (header_has_name, _1, "name"));
    

    您甚至可以使用 std::equal() 来完全避免 header_has_name 函数,但此时它变得有点难看。

    【讨论】:

      【解决方案3】:

      不幸的是,我认为编写 NotFindName 函子是最好的选择。

      【讨论】:

        猜你喜欢
        • 2016-12-25
        • 2015-05-14
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多