#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;
}
输出: