Using negation of UnaryPredicate in erase-remove idiom

check the std::not1 function. it does what you want.

v2.erase( std::remove_if(v2.begin(), v2.end(), std::not1(std::ptr_fun(is_odd))), v2.end() );

Live example

Anyway, if it is up to me plus C++11 is available I would prefere:

 v2.erase( std::remove_if(v2.begin(), v2.end(), [&](auto/* or the type */ const& item){return !is_odd(item);}), v2.end() );

because as far as I remember std::not1 was helpful before lambda was available.


You can use std::not1. Sadly, std::not1 requires a function object argument with nested argument_type and result_type types. That is, it can't be used directly. Instead, it is necessary to combine the use with std::ptr_fun when using the negator with a normal function:

    v2.erase( std::remove_if(v2.begin(), v2.end(), std::not1(std::ptr_fun(is_odd))), v2.end() );

At the last committee meeting std::not_fn was moved from the Library Fundamentals TS 2 into the working draft. That is, there is hope that with C++17 there is a better offer for a generic negator.

In general, the fun stops when you need to use any of the std::*_fun functions. As others have pointed out, it may be reasonable to use a lambda instead:

v2.erase( std::remove_if(v2.begin(), v2.end(), [](auto&& x){ return !::is_odd(x); }), v2.end() );

The use of a lambda function or a function object with an inline function call operator also has the advantage that the compiler has an easier time inlining the code.

Obviously, if you need to use C++ prior to C++11 the std::not1/std::ptr_fun approach is the easiest for immediate use an the use of a lambda function isn't even possible. In that case you may want to create a simple function object to support inlining:

struct not_odd {
    template <typename T>
    bool operator()(T const& value) const { return !::odd(value); }
};
// ...
v2.erase( std::remove_if(v2.begin(), v2.end(), not_odd()), v2.end() );