std::accumulate

#include <numeric>
accumulate形式有两种:

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

或者:

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

第一种是直接在初始值init上累加起始到终止范围内的全部值。
第二种是按照某种方式(BinaryOperation)对元素操作之后再累加到初始值上。BinaryOperation可以是函数指针或者一个对象。
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.

Binary operation接受两个参数,一个是type T类型的,一个是起始到终止范围内的某一个元素。

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

using namespace std;

int myfun(int x, int y) {
	return x + 2 * y;
}

struct MyClass
{
	int operator()(int x, int y) {
		return x + 3 * y;
	}
}object;

int main()
{
	int init = 100;
	vector<int> v = { 10, 20, 30 };
	
	cout << "using default accumulate: ";
	cout << accumulate(v.begin(), v.end(), init) << endl;//默认累加,结果为100+10+20+30

	cout << "using functional's minus: ";
	cout << accumulate(v.begin(), v.end(), init, minus<int>()) << endl;//使用minus,前者减去后者,100-10-20-30

	cout << "using function pointer: ";
	cout << accumulate(v.begin(), v.end(), init, myfun) << endl;//使用函数myfun,init加上2倍的后者,100+2*10+2*20+2*30

	cout << "using function object: ";
	cout << accumulate(v.begin(), v.end(), init, object) << endl;//使用函数对象,init加上3倍的后者,100+3*10+3*20+3*30

	return 0;
}

输出:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值