我有一些函数可以找到一个值:
struct FindPredicate
{
FindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t == _t;
}
private:
const SomeType& _t;
};
bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) {
return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end();
}
现在我想编写一个函数来检查 vector 的所有成员是否满足该谓词:
bool AllSatisfy(std::vector<SomeType>& v) {
/* ... */
}
一种解决方案是使用 std::count_if
算法。
有谁知道涉及否定谓词的解决方案?
最佳答案
最好的解决办法是使用STL functional library .通过从 unary_function<SomeType, bool>
派生谓词,然后您就可以使用 not1
函数,这正是您需要的(即否定一元谓词)。
你可以这样做:
struct FindPredicate : public unary_function<SomeType, bool>
{
FindPredicate(const SomeType& t) : _t(t) {}
bool operator()(const SomeType& t) const {
return t == _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
return find_if(v.begin(),
v.end(),
not1(FindPredicate(valueToFind))) == v.end();
}
如果您想推出自己的解决方案(恕我直言,这不是最佳选择...),那么您可以编写另一个谓词来否定第一个谓词:
struct NotFindPredicate
{
NotFindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t != _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v) {
return find_if(v.begin(),
v.end(),
NotFindPredicate(valueToFind)) == v.end();
}
或者你可以做得更好,写一个模板仿函数否定器,比如:
template <class Functor>
struct Not
{
Not(Functor & f) : func(f) {}
template <typename ArgType>
bool operator()(ArgType & arg) { return ! func(arg); }
private:
Functor & func;
};
你可以使用如下:
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
FindPredicate f(valueToFind);
return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
当然,后一种解决方案更好,因为您可以将 Not 结构与您想要的每个仿函数一起重用。
关于algorithm - 如何在 C++ (STL) 中否定仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/265228/