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(); }
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) { /* ... */ }
One solution is to use the std::count_if algorithm.
Does anyone know a solution that involves negating the 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 thenot1function, which does precisely what you need (i.e. negating a unary predicate).Here is how you could do that :
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 :
Or you could do better and write a template functor negator, like :
that you could use as follow :
Of course, the latter solution is better because you can reuse the Not struct with every functor you want.