accumulate定义在 numeric 中,作用有两个,一个是累加求和,另一个是自定义类型数据的处理。

头文件

#include <numeric>

原型

默认求累加和

template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}

自定义数据的处理

template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

参数

  • first,last:迭代器,指向要操作的序列的区间[first, last)。first指向的元素参与计算,last不参与计算;
  • init:初始值,如在init的基础上进行求和计算;
  • binary_op:Binary operation taking an element of type T as first argument and an element in the range as second, and which returns a value that can be assigned to type T. This can either be a function pointer or a function object. The operation shall not modify the elements passed as its arguments.

案例

// accumulate example
#include <iostream> // std::cout
#include <functional> // std::minus
#include <numeric> // std::accumulate int myfunction (int x, int y) {return x+2*y;}
struct myclass {
int operator()(int x, int y) {return x+3*y;}
} myobject; int main () {
int init = 100;
int numbers[] = {10,20,30}; std::cout << "using default accumulate: ";
std::cout << std::accumulate(numbers,numbers+3,init);
std::cout << '\n'; std::cout << "using functional's minus: ";
std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
std::cout << '\n'; std::cout << "using custom function: ";
std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
std::cout << '\n'; std::cout << "using custom object: ";
std::cout << std::accumulate (numbers, numbers+3, init, myobject);
std::cout << '\n'; return 0;
}

输出:

using default accumulate: 160
using functional's minus: 40
using custom function: 220
using custom object: 280

最新文章

  1. nginx中配置pathinfo模式示例
  2. TransactionScope类的使用
  3. xmpp整理笔记:聊天信息的发送与显示
  4. 数据分页处理系列之二:HBase表数据分页处理
  5. Linux操作系统下三种配置环境变量的方法
  6. ZJOI 游记
  7. ECSHOP数据表结构完整仔细说明教程
  8. SQL用法总结
  9. phpcms 如何获取文章
  10. C++ ofstream和ifstream具体的方法和C语言file说明
  11. iOS 横竖屏适配 笔记
  12. Java 读书笔记 (五) 目标数据类型转换
  13. code runner 使用教程
  14. GitHub:本地项目上传与团队协作
  15. Spring 实现事务的三种方式
  16. 【Linux基础】awk命令
  17. RxJava2.0的使用详解
  18. CSS变形transform(2d)
  19. 【【C++ Primer 第15章】 虚析构函数
  20. Problem E: 用链表实现约瑟夫环

热门文章

  1. WDA学习(25):DateNavigator使用
  2. RMAN架构
  3. iOS 12.3 - iOS 13.X 爱思助手越狱教程
  4. java使用minio上传下载文件
  5. C# WPF 自学 MVVM简单介绍
  6. win电脑查看wifi密码的方法
  7. 爱心代码_HTML
  8. wampserver APACHE配置文件 和 单独安装APACHE 的配置文件 的区别
  9. Tomcat启动—本地文件夹
  10. 二,使用axios