STL算法-accumlate

来源:互联网 发布:windows死循环脚本 编辑:程序博客网 时间:2024/05/07 06:31

包含在头文件numeric  中


accumlate 源码:

First version

template<class InputIt, class T>T accumulate(InputIt first, InputIt last, T init){    for (; first != last; ++first) {        init = init + *first;    }    return init;}
Second version
template<class InputIt, class T, class BinaryOperation>T accumulate(InputIt first, InputIt last, T init,              BinaryOperation op){    for (; first != last; ++first) {        init = op(init, *first);    }    return init;}
example:

#include <iostream>#include <vector>#include <numeric>#include <string> int multiply(int x, int y){    return x*y;} std::string magic_function(std::string res, int x){    return res += (x > 5) ? "b" : "s";} int main(){    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};     int sum = std::accumulate(v.begin(), v.end(), 0);    int product = std::accumulate(v.begin(), v.end(), 1, multiply);    std::string magic = std::accumulate(v.begin(), v.end(), std::string(),                                         magic_function);     std::cout << sum << '\n'              << product << '\n'              << magic << '\n';}

结果:

553628800sssssbbbbb

0 0
原创粉丝点击