C++ accumulate函數(shù)詳細(xì)介紹和具體案例
一、函數(shù)簡單介紹
accumulate是numeric
庫中的一個(gè)函數(shù),主要用來對指定范圍內(nèi)元素求和,但也自行指定一些其他操作,如范圍內(nèi)所有元素相乘、相除等。
使用前需要引入相應(yīng)的頭文件。
#include <numeric>
- 函數(shù)共有四個(gè)參數(shù),其中前三個(gè)為必須,第四個(gè)為非必需。
- 若不指定第四個(gè)參數(shù),則默認(rèn)對范圍內(nèi)的元素進(jìn)行累加操作。
accumulate(起始迭代器, 結(jié)束迭代器, 初始值, 自定義操作函數(shù))
二、具體使用場景
1. 計(jì)算數(shù)組中所有元素的和
#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 0); // 初值0 + (1 + 2 + 3 + 4 +... + 10) cout << sum << endl; // 輸出55 return 0; }
2. 計(jì)算數(shù)組中所有元素的乘積
需要指定第四個(gè)參數(shù),這里使用的是乘法函數(shù) multiplies<type>()
, type根據(jù)元素的類型選擇。
#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 1, multiplies<int>()); // 初值1 * (1 * 2 * 3 * 4 *... * 10) cout << sum << endl; // 輸出3628800 return 0; }
3. 計(jì)算數(shù)組中每個(gè)元素乘以3之后的和
#include <iostream> #include <vector> #include <numeric> using namespace std; int fun(int acc, int num) { return acc + num * 3; // 計(jì)算數(shù)組中每個(gè)元素乘以3 } int main() { vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 0, fun); cout << sum << endl; // 輸出 165 return 0; }
4.計(jì)算數(shù)組中每個(gè)元素減去3之后的和
#include <iostream> #include <vector> #include <numeric> using namespace std; int fun(int acc, int num) { return acc + (num - 3) ; // 計(jì)算數(shù)組中每個(gè)元素減去3之后的和 } int main() { vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = accumulate(arr.begin(), arr.end(), 0, fun); cout << sum << endl; // 輸出25 return 0; }
5.計(jì)算班級(jí)內(nèi)學(xué)生的平均分
#include <iostream> #include <vector> #include <numeric> using namespace std; struct Student { string name; int score; Student() {}; // 無參構(gòu)造函數(shù) Student(string name, int score) : name(name), score(score) {}; // 有參構(gòu)造函數(shù) }; int fun(int acc, Student b) { return a + 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(); // 總分/學(xué)生數(shù) cout << avg_score << endl; return 0; }
6.拼接字符串
C++中字符串之間也可以使用
+
,即拼接兩個(gè)字符串。
#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<string> words{"this ", "is ", "a ", "sentence!"}; string init, res; res = accumulate(words.begin(), words.end(), init); // 連接字符串 cout << res << endl; // this is a sentence! return 0; }
到此這篇關(guān)于C++ accumulate函數(shù)詳細(xì)介紹和具體案例的文章就介紹到這了,更多相關(guān)C++ accumulate函數(shù) 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章

C++ 使用PrintWindow實(shí)現(xiàn)窗口截圖功能

Mingw64編譯wxWidgets 3.0.2常見錯(cuò)誤分析