Michael Sync
Michael Sync

Reputation: 4994

C++ How to have "NOT" (!) in Predicate?

It might be a stupid question but just wonder if there is any workaround. :)

Is there any way to have "Not" in Predicate?

Example:

std::remove_if(s.begin(), s.end(), !IsCorrect); 
//                                 ^

Or, Do I have to create IsNotCorrect function anyways?

Upvotes: 8

Views: 1189

Answers (2)

user2556165
user2556165

Reputation:

Also you can try brutforce like this to any predicate in C++11

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

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279245

You can do it using std::not1, which negates a unary predicate:

#include <functional>

std::remove_if(s.begin(), s.end(), std::not1(std::ptr_fun(IsCorrect)));

If IsCorrect is an Adaptable Function then you don't need ptr_fun, but if it's just a plain function then you do.

Upvotes: 18

Related Questions