用于累加数组元素
普通用法:accumulate(首指针,末指针,累加初始值)
除了对数字求和还可以连接字符串
#include <bits/stdc++.h>
using namespace std;
vector<string> v; vector<int> vs;
int a[11];
int main(int argc, char const *argv[]) {
v.push_back("123"); v.push_back("456"); v.push_back("asd");
cout << accumulate(v.begin(), v.end(), string("")) << endl;
vs.push_back(1); vs.push_back(3);
cout << accumulate(vs.begin(), vs.end(), 0) << endl;
for (int i = 1; i <= 10; i++) a[i] = i;
cout << accumulate(a + 1, a + 10 + 1, 0) << endl;
}
对于自定义类型的求和需要自己写函数,作为第四个参数
比如对下面这个node类型的x,y求和:
struct node {int x, y;}e[11];
for (int i = 1; i <= 10; i++) e[i].x = e[i].y = i;
cout << accumulate(e + 1, e + 10 + 1, 0, [](int a, node w) {return a + w.x + w.y;}) << endl;