vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 0); cout << sum << endl; // 输出55
乘积
1 2 3
vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 1, multiplies<int>()); cout << sum << endl; // 输出3628800
字符串拼接
1 2 3 4 5
// 能进行拼接的原因是string类定义了+方法 vector<string> words{"this ", "is ", "a ", "sentence!"}; string init, res; res = accumulate(words.begin(), words.end(), init); // 连接字符串 cout << res << endl; // this is a sentence!
自定义操作1
1 2 3 4 5
intfunc(int acc, int num){ return (3 * acc + 13 * num + 113) % 1634246007; // hash } vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 0, func);