常用算术生成算法
学习目标:
-
掌握常用的算术生成算法
注意:
-
算术生成算法属于小型算法,使用时包含的头文件为
#include <numeric>
算法简介:
-
accumulate
// 计算容器元素累计总和 -
fill
// 向容器中添加元素
accumulate
功能描述:
-
计算区间内容器元素累计总和
函数原型:
-
accumulate(iterator beg, iterator end, value);
-
beg
:开始迭代器 -
end
:结束迭代器 -
value
:起始值
-
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main() {
// 创建一个包含多个元素的 vector
vector<int> v = {1, 2, 3, 4, 5};
// 输出容器的内容
cout << "容器的内容: ";
for (auto it = v.begin(); it != v.end(); it++) {
cout << (*it) << " ";
}
cout << endl;
// 计算容器元素的总和,起始值为 0
int sum = accumulate(v.begin(), v.end(), 0);
// 输出总和
cout << "容器元素的总和: " << sum << endl;
return 0;
}
fill
功能描述:
-
向容器中填充指定的元素
函数原型:
-
fill(iterator beg, iterator end, value);
-
beg
:开始迭代器 -
end
:结束迭代器 -
value
:填充的值
-
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// 创建一个空的 vector 容器
vector<int> v = {1,2,3,4,5};
// 输出填充前的容器内容
cout << "填充前的容器内容: ";
for (auto it = v.begin(); it != v.end(); it++) {
cout << (*it) << " ";
}
cout << endl;
// 使用 fill 函数将容器中的元素全部填充为 10
fill(v.begin(), v.end(), 10);
// 输出填充后的容器内容
cout << "填充后的容器内容: ";
for (auto it = v.begin(); it != v.end(); it++) {
cout << (*it) << " ";
}
cout << endl;
return 0;
}