代码之家  ›  专栏  ›  技术社区  ›  missingfaktor Kevin Wright

C++中的“滤波”高阶函数

  •  7
  • missingfaktor Kevin Wright  · 技术社区  · 14 年前

    filter 函数语言中的函数?

    我能找到的最接近的函数是 std::remove_copy_if 但这似乎与我的愿望背道而驰。做 boost::lambda not 在哈斯克尔?我可以否定我的谓词,并将其与 那么。

    滤波器 C++中的函数;我只是问标准库和/或升压是否已经提供了这样的函数。

    4 回复  |  直到 14 年前
        1
  •  6
  •   wilx    14 年前

    包括 <functional> std::not1 cont.erase (std::remove_if (cont.begin (), cont.end (), std::not1 (pred ())), cont.end ());

        2
  •  6
  •   Arzar    14 年前

    有一个等效的过滤器 Boost.Range

    #include <vector>
    #include <boost/lambda/lambda.hpp>
    #include <boost/range/algorithm_ext/push_back.hpp>
    #include <boost/range/adaptor/filtered.hpp>
    
    using namespace boost::adaptors;
    using namespace boost::lambda;
    
    int main()
    {
        std::vector<int> v = {3, 2, 6, 10, 5, 2, 45, 3, 7, 66};
        std::vector<int> v2;
        int dist = 5;
    
        boost::push_back(v2, filter(v, _1 > dist));
        return 0;
    }
    
        3
  •  1
  •   Cubbi    14 年前

    filter_iterator .

    比如说,你有一个自然数的向量,还有一个你想应用到一对迭代器上的函数,它应该只看到过滤后的向量,只有奇数:

    #include <algorithm>
    #include <vector>
    #include <iterator>
    #include <numeric>
    #include <iostream>
    #include <boost/iterator/filter_iterator.hpp>
    template<typename Iter>
    void do_stuff(Iter beg, Iter end)
    {
        typedef typename std::iterator_traits<Iter>::value_type value_t;
        copy(beg, end, std::ostream_iterator<value_t>(std::cout, " "));
        std::cout << '\n';
    }
    struct is_even {
            bool operator()(unsigned int i) const { return i%2 == 0; }
    };
    int main()
    {
            std::vector<unsigned int> v(10, 1);
            std::partial_sum(v.begin(), v.end(), v.begin()); // poor man's std::iota()
    
            // this will print all 10 numbers
            do_stuff(v.begin(), v.end());
            // this will print just the evens
            do_stuff(boost::make_filter_iterator<is_even>(v.begin(), v.end()),
                     boost::make_filter_iterator<is_even>(v.end(), v.end()));
    
    }
    
        4
  •  1
  •   Mike Seymour    14 年前

    使用 remove_if remove_copy_if ,与 not1 (定义见 <functional> )反转谓词。像这样:

    #include <algorithm>
    #include <functional>
    
    template <class ForwardIterator, class Predicate>
    ForwardIterator filter(ForwardIterator first, ForwardIterator last, 
                           Predicate pred)
    {
        return std::remove_if(first, last, std::not1(pred));
    }
    
    template <class InputIterator, class OutputIterator, class Predicate>
    OutputIterator filter_copy(InputIterator first, InputIterator last, 
                               OutputIterator result, Predicate pred)
    {
        return std::remove_copy_if(first, last, result, std::not1(pred));
    }