accumulate函数解析

函数介绍

accumulate是numeric库中的一个函数,主要用来对指定范围内元素求和,但也自行指定一些其他操作,如范围内所有元素相乘、相除、自定义操作等。

使用前导入头文件。

1
2
3
#include<numeric>
accumulate(起始迭代器, 结束迭代器, 初始值[, 自定义操作函数])
// 第四个参数忽略则默认进行求和计算

求和

1
2
3
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
int func(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);

自定义操作2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Student {
string name;
int score;
Student() {};
Student(string name, int score) : name(name), score(score) {};
};

int fun(int acc, Student b) {
return acc + b.score;
}

int main() {
vector<Student> arr;
arr.emplace_back("Alice", 82);
arr.emplace_back("Bob", 91);
arr.emplace_back("Lucy", 85);
arr.emplace_back("Anna", 60);
arr.emplace_back("June", 73);
int avg_score = accumulate(arr.begin(), arr.end(), 0, fun) / arr.size(); // 总分/学生数
cout << avg_score << endl;
return 0;
}