C++ STL 之 accumulate 累积函数

C++ STL 之 accumulate 累积函数

编码文章call10242025-07-02 18:43:376A+A-

// 头文件

#include <numeric>

#include <vector>

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 数组初始化

auto sum = std::accumulate(arr, arr + 10, 0); // 数组元素求和

cout << sum << endl;

vector<int> v {1,3,5,7,9 }; // 容器 vector 初始化

auto total = accumulate(v.begin(), v.end(), 0); // vector 容器求和

cout << total << endl;

====================================================

函数原型:

template <class InputIt, class T>

T accumulate(InputIt first, InputIt last, T init); // 参数:输入数据起始,输入数据结束,初始值

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4