Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 619
Michael Sync Avatar asked Oct 30 '10 19:10

Michael Sync


2 Answers

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.

like image 137
Steve Jessop Avatar answered Nov 18 '22 06:11

Steve Jessop


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...); }
like image 1
3 revsuser2556165 Avatar answered Nov 18 '22 06:11

3 revsuser2556165