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