C++ STL 中的数组求和


数组是一个线性数据结构,它在连续的内存位置存储相同数据类型的元素。

数组求和是数组中所有元素的总和。

C++ 编程语言中,有多种方法可以找到数组的和。

经典方法

查找数组所有元素和的基本方法是遍历数组元素并将元素的值添加到 sum 变量。

算法

Step 1 : For i from 0 to n-1, follow step 2 ;
Step 2 : sum = sum + arr[i]
Step 3 : print sum.

示例

 在线演示

#include <iostream>
using namespace std;
int main (){
   int arr[] = { 2, 5, 7, 8, 2, 6, 9 };
   int n = 7, sum = 0;
   for(int i = 0; i<n ; i++){
      sum+=arr[i];
   }
   cout<<"The array sum is "<<sum;
   return 0;
}

输出

The array sum is 39

使用 accumulate 方法

C++ 中的accumulate() 方法用于查找数组的和。此函数可以从C++ 中的 numeric 库访问。

语法

accumulate(array_name , array_name+length , sum);

示例

 在线演示

#include <iostream>
#include <numeric>
using namespace std;
int main (){
   int arr[] = { 2, 5, 7, 8, 2, 6, 9 };
   int n = 7, sum = 0;
   sum = accumulate(arr, arr+n, sum);
   cout<<"The array sum is "<<sum;
   return 0;
}

输出

The array sum is 39

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

使用向量求和

你也可以对向量使用accumulate() 函数。它将返回数组(向量形式)的和。

示例

 在线演示

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int arraySum(vector<int> &v){
   int initial_sum = 0;
   return accumulate(v.begin(), v.end(), initial_sum);
}
int main(){
   vector<int> v{12, 56, 76, 2, 90 , 3} ;
   int sum = 0;
   sum=accumulate(v.begin(), v.end(), sum);
   cout<<"The sum of array is "<<sum;
   return 0;
}

输出

The sum of array is 239

更新于:2023年9月14日

33K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告