美文网首页
C++ STL accumulate 使用说明

C++ STL accumulate 使用说明

作者: book_02 | 来源:发表于2019-10-17 17:17 被阅读0次

说明

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/

相关文章

  • C++ STL accumulate 使用说明

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

  • 读书笔记17.06.03

    C++ STL:Listlist是C++标准模版库(STL,Standard Template Library)中...

  • [C++] STL 容器

    参考:[C++] STL 容器 (一) - 基本介紹[C++] STL 容器 (二) - Iterator 部分示例:

  • C++ STL 学习笔记

    C++ STL 学习笔记

  • STL之参考文献

    C++标准库是离不开模板的,STL占了C++标准库80%以上。 学习STL(c++ 98)的主要参考: gcc 3...

  • C++ STL multiplies 使用说明

    说明 std::multiplies是乘法的二元函数对象。 常被用于std::transform或者std::ac...

  • C++ STL shuffle 使用说明

    说明 使用一个随机数产生器来打乱[first, last)之间元素的顺序。 有3个参数,前2个参数指定容器的范围,...

  • C++ accumulate()函数

    作用 accumulate函数将一段数字从头到尾累加起来,或者使用指定的运算符进行运算accumulate函数的前...

  • 任务列表

    C++ 《C++ primer》、《STL源码解析》、《effective C++》、《深度搜索c++对象模型》 ...

  • STL初认识

    一 C++ 与STL 历史 STL全称standard template library,由Alexander S...

网友评论

      本文标题:C++ STL accumulate 使用说明

      本文链接:https://www.haomeiwen.com/subject/jpjvmctx.html