如何使用 STL 在 C++ 中找到数组元素的和?
这里,我们将了解如何求一个数组中所有元素的和。所以如果数组是这样的:[12, 45, 74, 32, 66, 96, 21, 32, 27],那么和将为:405。因此这里我们必须使用 accumulate() 函数来解决这个问题。该函数的描述存在于 <numeric> 头文件中。
示例
#include<iostream>
#include<numeric>
using namespace std;
int main() {
int arr[] = {12, 45, 74, 32, 66, 96, 21, 32, 27};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Array is like: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\nSum of all elements: " << accumulate(arr, arr + n, 0);
}输出
Array is like: 12 45 74 32 66 96 21 32 27 Sum of all elements: 405
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP