C++ STL accumulate 使用说明

2019-10-17  本文已影响0人  book_02

说明

std::accumulate 用于对容器[first,last)内的元素和初始值init进行累积运算。

前2个参数指定容器的范围,第3个参数指定初始值。
返回值为累加的结果,其返回类型就是其第三个实参的类型。

函数签名如下:

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

默认的运算是第三个参数的加法运算,如果第三个参数是int,运算就是数值加法运算;如果第三个参数是string,运算就是字符串的拼接。

可以自定义运算,自定义的运算作为第四个参数,函数签名如下:

template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init,
              BinaryOperation op );

头文件

#include <numeric>

例子:累加

#include <iostream>
#include <vector>
#include <numeric>

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

    std::cout << "sum: " << sum << std::endl;

    return 0;
}

结果如下:

sum: 55

例子:累乘

#include <iostream>
#include <vector>
#include <numeric>

int main()
{
    std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());

    std::cout << "product: " << product << std::endl;

    return 0;
}

结果如下:

product: 3628800

例子:字符串拼接

#include <iostream>
#include <vector>
#include <numeric>
#include <string>

int main()
{
   std::vector<std::string> v{ "hello", "from", "accumulate" };

   auto dash_fold = [](std::string a, std::string b) {
       return (a+"-"+b);
   };

   std::string s = accumulate(v.begin(), v.end(), std::string("receive"), dash_fold);

   std::cout << "dash-separated string : "<< s << std::endl;

    return 0;
}

结果如下:

dash-separated string : receive-hello-from-accumulate

参考

https://zh.cppreference.com/w/cpp/algorithm/accumulate
http://www.cplusplus.com/reference/numeric/accumulate/

上一篇 下一篇

猜你喜欢

热点阅读