C++-使用accumulate来实现find_if算法

C++函数式编程里主要介绍了folding【折叠】的使用,在C++STL中,accumulate(求和)正是其中的佼佼者,我使用了这个标准库函数实现了另一个标准库函数find_if。以下是代码

template <typename Input, typename UnaryPredicate>
Input find_if_a(Input first, Input last, UnaryPredicate pred) //传入一对迭代器和一个谓词
{
    //假设accmulate的第三个参数,也就是初始值的类型是R,第一个和第二个函数,也就是那对迭代器解引用后的类型为T,
    //那么第四个参数——二元函数对象的参数设置就该是R,T的顺序
    //使用decltype让编译器自己推测出传入容器的数据类型, 使用捕捉捕捉pred 最后用lambda组合一下,形成一个二元函数对象。
    return first + std::accumulate(first, last, 0,
                                   [pred](int b, decltype(*first) a) {
                                       if (pred(a))
                                       {
                                           return b;
                                       }
                                       else
                                       {
                                           return b + 1;
                                       }
                                   }); //返回起始范围+求和结果
}
int main()
{
    std::vector<int> a{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 14};
    auto f = std::find_if(a.begin(), a.end(), [](int &al) { return al > 1; });
    auto b = find_if_a(a.begin(), a.end(), [](int &al) { return al > 1; });
    std::for_each(f, a.end(), [](int ab) { std::cout << ab; });
    std::cout << '\n';
    std::for_each(b, a.end(), [](int ab) { std::cout << ab; });
    system("pause");
}

输出结果是一致的。

 

posted @ 2021-02-08 04:52  扎坦诺斯  阅读(108)  评论(0)    收藏  举报