Negative filter

Is an achievable / negative change in an adapter with a reinforced filter possible, e.g.

std::vector<int> v = {1, 2, 3, 4, 5};
for(auto i : v | !filtered(is_even))
    std::cout << i << std::endl; // prints 1,3,5

instead of doing negation inside a lambda expression?

Motivation: I work a lot with filtered and lambda functions, however, when I use a filter more than once, I usually reorganize it into a custom filter, for example.

for(auto i : v | even) // note: my filters are more complex than even.
    std::cout << i << std::endl; // prints 2,4

Now that I need negation, I create a custom filter for them, for example.

for(auto i : v | not_even)
    std::cout << i << std::endl; // prints 1,2,3

but I would be best off hiding a negative filter like

for(auto i : v | !even)
    std::cout << i << std::endl; // prints 1,2,3
+5
source share
2 answers

Here is what I came up with as soon as possible:

#include <boost/range/adaptors.hpp>
#include <boost/functional.hpp>
#include <iostream>

namespace boost { 
    namespace range_detail { 

        template <typename T>
            auto operator!(filter_holder<T> const& f) -> decltype(adaptors::filtered(boost::not1(f.val)))
            {
                return adaptors::filtered(boost::not1(f.val));
            }
    }
}

int main()
{
    using namespace boost::adaptors;
    int const v[] = { 1, 2, 3, 4 };

    std::function<bool(int)> ll = [](int i){return 0 == (i%2);}; // WORKS
    // bool(*ll)(int) = [](int i){return 0 == (i%2);};           // WORKS
    // auto ll = [](int i){return 0 == (i%2);};                  // not yet

    auto even = filtered(ll);

    for (auto i : v | !even)
    {
        std::cout << i << '\n';
    }
}

Watch live on liveworkspace.org

, function pointer std::function<...>, ( GCC 4.7.2)

+7

, , . , .

, namespace boost::range_detail.

++ 17

std::not_fn .

#include <boost/range/adaptors.hpp>
#include <functional>
#include <iostream>

struct is_even
{
    bool operator()( int x ) const { return x % 2 == 0; }
};

int main()
{
    using namespace boost::adaptors;
    int const v[] = { 1, 2, 3, 4 };

    for( auto i : v | filtered( std::not_fn( is_even{} ) ) )
    {
        std::cout << i << ' ';
    }
}

Live Demo

++ 11, ++ 14

std::not1 . , , argument_type , operator() operator().

#include <boost/range/adaptors.hpp>
#include <functional>
#include <iostream>

struct is_even
{
    using argument_type = int;
    bool operator()( int x ) const { return x % 2 == 0; }
};

int main()
{
    using namespace boost::adaptors;
    int const v[] = { 1, 2, 3, 4 };

    for( auto i : v | filtered( std::not1( is_even{} ) ) )
    {
        std::cout << i << ' ';
    }
}

Live Demo

0

All Articles