在C ++中“过滤”高阶函数

时间:2010-09-03 11:26:59

标签: c++ functional-programming higher-order-functions

C ++标准库和/或Boost是否与函数式语言中的filter函数类似?

我能找到的最接近的功能是std::remove_copy_if,但它似乎与我想要的相反。 boost::lambda是否有任何函数来获取谓词的否定版本(类似于Haskell中的not)?我可以否定我的谓词并将其与std::remove_copy_if一起使用。

请注意,我不是在询问如何在C ++中编写filter函数;我只想问标准库和/或Boost是否已经提供了这样的功能。

提前致谢。

4 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:6)

<functional>添加std::not1并尝试cont.erase (std::remove_if (cont.begin (), cont.end (), std::not1 (pred ())), cont.end ());

答案 2 :(得分:1)

我发现通过组合boost.iterators可以解决许多功能风格的任务。为此,它有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()));

}

答案 3 :(得分:1)

使用remove_ifremove_copy_ifnot1(在<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));
}