我怎么能否定在C ++(STL)函子?我怎么能、STL

2023-09-10 23:35:35 作者:那与爱无关″

我有一些功能找到一个值:

I have some function to find a value:

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();
}

现在我想编写一个函数来检查,如果一个向量的所有成员都满足了predicate:

Now I would like to write a function that checks if all members of a vector satisfy that predicate:

bool AllSatisfy(std::vector<SomeType>& v) {
    /* ... */
}

一种解决方案是使用的std :: count_if 算法。

有谁知道,包括否定了predicate的解决方案?

Does anyone know a solution that involves negating the predicate?

推荐答案

最好的解决方法是使用 STL功能库。通过从 unary_function&LT派生的predicate; SOMETYPE,布尔&GT; ,你就那么可以使用 NOT1 函数,该函数precisely你所需要的(即否定一元predicate)。

The best solution is to use the STL functional library. By deriving your predicate from unary_function<SomeType, bool> , you'll then be able to use the not1 function, which does precisely what you need (i.e. negating a unary predicate).

下面是你如何能做到这一点:

Here is how you could do that :

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();
}

如果你想推出自己的解决方案(这是,恕我直言,不是最好的选择...),好了,你可以写另一个predicate那就是否定第一种:

If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :

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();
}

或者你可以做的更好,并编写模板仿函数否定符,如:

Or you could do better and write a template functor negator, like :

template <class Functor>
struct Not
{
    Not(Functor & f) : func(f) {}

    template <typename ArgType>
    bool operator()(ArgType & arg) { return ! func(arg); }

  private:
    Functor & func;
};

,你可以如下使用:

that you could use as follow :

bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
    FindPredicate f(valueToFind);
    return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}

当然,后一种解决方案是更好,因为你可以重复使用的不的结构与您希望每一个函子。

Of course, the latter solution is better because you can reuse the Not struct with every functor you want.