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

使用累计方法

c ++中的accumulate方法用于查找数组和。可以从c ++中的数字库访问此函数。

语法

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

使用向量总和

您也可以对向量使用累加功能。它将返回向量的数组之和。

示例

#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