常用算術生成算法
學習目標:
-
掌握常用的算術生成算法
注意:
-
算術生成算法屬于小型算法,使用時包含的頭文件為
#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() {// 創建一個包含多個元素的 vectorvector<int> v = {1, 2, 3, 4, 5};// 輸出容器的內容cout << "容器的內容: ";for (auto it = v.begin(); it != v.end(); it++) {cout << (*it) << " ";}cout << endl;// 計算容器元素的總和,起始值為 0int 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 函數將容器中的元素全部填充為 10fill(v.begin(), v.end(), 10);// 輸出填充后的容器內容cout << "填充后的容器內容: ";for (auto it = v.begin(); it != v.end(); it++) {cout << (*it) << " ";}cout << endl;return 0;
}