【问题标题】:C++ How to have "NOT" (!) in Predicate?C ++如何在谓词中有“NOT”(!)?
【发布时间】:2010-10-30 19:42:31
【问题描述】:

这可能是一个愚蠢的问题,但只是想知道是否有任何解决方法。 :)

有没有办法在谓词中添加“不”?

例子:

std::remove_if(s.begin(), s.end(), !IsCorrect); 
//                                 ^

或者,我是否必须创建 IsNotCorrect 函数?

【问题讨论】:

标签: c++


【解决方案1】:

您可以使用std::not1 来实现,它否定一元谓词:

#include <functional>

std::remove_if(s.begin(), s.end(), std::not1(std::ptr_fun(IsCorrect)));

如果IsCorrect 是一个自适应函数,那么你不需要ptr_fun,但如果它只是一个普通函数,那么你就需要。

【讨论】:

  • 请注意 std::ptr_fun 已弃用。我认为std::ref 可以在这里替代。
  • @ECrownofFire:对,ptr_fun 在 C++11 中已过时。我想原则上有人有一个项目,可以通过在 2011 年之前提出的关于 SO 的所有 C++ 问题,并使用 C++11(和/或 C++14)等价物更新他们的答案,那里有更好的解决方案;-)
【解决方案2】:

您也可以像这样对 C++11 中的任何谓词尝试 brutforce

template<class Predicate>
class not {
    //Has it's inverse predicate
    Predicate _Pred;
public:

    //Construct with arguments
    //required to construct _Pred
    template<class... Args>
    not(Args&&... args);

    //bool operator() with
    //_Pred arguments
    template<class... Args>
    bool operator()(Args&&... args) const;
};

template<class Predicate>
template<class... Args>
not<Predicate>::not(Args&&... args): _Pred(args...) {}

template<class Predicate>
template<class... Args>
bool not<Predicate>::operator()
    (
    Args&&... args
    ) const { return !_Pred(args...); }

【讨论】:

  • 最好在构造函数和函数调用运算符中都转发参数:“std::forward( args ) ...”。不错的答案。
  • @Ash 我在开始学习可变参数模板的时候回答了这个问题。当然应该有转发使用)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-17
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多