一、函数简单介绍

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

头文件:

#include <numeric>


函数共有四个参数,其中前三个为必须,第四个为非必需。

若不指定第四个参数,则默认对范围内的元素进行累加操作。

accumulate(起始迭代器, 结束迭代器, 初始值, 自定义操作函数)

二、具体使用场景


1. 计算数组中所有元素的和
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main() {
	vector<int> arr{ 1, 2, 3, 4, 5, 6, 7 };

	int sum = accumulate(arr.begin(), arr.end(), 0);
	// 初值0 + (1 + 2 + 3 + 4 +... + 7)

	cout << sum << endl;	//28
	return 0;
}

2. 计算数组中所有元素的乘积

需要指定第四个参数,这里使用的是乘法函数 multiplies<type>(), type根据元素的类型选择。

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

using namespace std;

int main() {
	vector<int> arr{ 1, 2, 3, 4, 5, 6, 7};

	int sum = accumulate(arr.begin(), arr.end(), 1, multiplies<int>());
	// 初值1 * (1 * 2 * 3 * 4 *... * 7)

	cout << sum << endl;	//5040
	return 0;
}

3. 计算数组中每个元素乘以3之后的和
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int fun(int acc, int num) {
	return acc + num * 3;// 计算数组中每个元素乘以3
}

int main() {
	vector<int> arr{ 1, 2, 3, 4, 5, 6, 7};
	int sum = accumulate(arr.begin(), arr.end(), 0, fun);
	cout << sum << endl;	//84
	return 0;
}

4.计算数组中每个元素减去3之后的和
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int fun(int acc, int num) {
	return acc + (num - 3);// 计算数组中每个元素减去3之后的和
}

int main() {
	vector<int> arr{ 1, 2, 3, 4, 5, 6, 7};
	int sum = accumulate(arr.begin(), arr.end(), 0, fun);
	cout << sum << endl;    //7
	return 0;
}

5.计算班级内学生的平均分
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

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("A", 86);
	arr.emplace_back("B", 91);
	arr.emplace_back("C", 85);
	arr.emplace_back("D", 66);
	arr.emplace_back("E", 75);
	int avg_score = accumulate(arr.begin(), arr.end(), 0, fun) / arr.size();// 总分/学生数
	cout << avg_score << endl;//80
	return 0;
}


6.拼接字符串

C++中字符串之间也可以使用+,即拼接两个字符串。

函数第三个参数:init表示字符串的初始值

#include <iostream>
#include <vector>
#include <string>
#include <numeric>

using namespace std;

int main() {
	vector<string> words{ "this ", "is ", "a ", "dog!" };
	string init = "hello, ", res;
	res = accumulate(words.begin(), words.end(), init);// 连接字符串
	cout << res << endl;// hello, this is a dog!
	return 0;
}

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐