【发布时间】:2010-10-30 19:42:31
【问题描述】:
这可能是一个愚蠢的问题,但只是想知道是否有任何解决方法。 :)
有没有办法在谓词中添加“不”?
例子:
std::remove_if(s.begin(), s.end(), !IsCorrect);
// ^
或者,我是否必须创建 IsNotCorrect 函数?
【问题讨论】:
标签: c++
这可能是一个愚蠢的问题,但只是想知道是否有任何解决方法。 :)
有没有办法在谓词中添加“不”?
例子:
std::remove_if(s.begin(), s.end(), !IsCorrect);
// ^
或者,我是否必须创建 IsNotCorrect 函数?
【问题讨论】:
标签: c++
您可以使用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 可以在这里替代。
ptr_fun 在 C++11 中已过时。我想原则上有人有一个项目,可以通过在 2011 年之前提出的关于 SO 的所有 C++ 问题,并使用 C++11(和/或 C++14)等价物更新他们的答案,那里有更好的解决方案;-)
您也可以像这样对 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...); }
【讨论】: