algorithm - 如何在 C++ (STL) 中否定仿函数?

标签 algorithm stl c++

我有一些函数可以找到一个值:

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/

相关文章:

algorithm - 具有最大权重的单词分区

C++ std::array 警告

c++ - C++ 的可调整大小的字符缓冲区容器类型

iPhone 的 C++ 编译(STL 问题?)

c++ - 没有完全指定模板作为 C++ 中的模板参数

c++ - 在控制台C++上获取当前字体的大小

algorithm - 基本的飞行旅行计划

c - 以任意顺序在矩阵中查找模式?

python - 如何使使用 for 循环的 python 代码运行得更快?

c++ - difftime 和 strftime 值中的差异