當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ 數組求和accumulate()用法及代碼示例

在C++中,我們可以使用accumulate()快速找到數組總和

// C++ program to demonstrate working of accumulate() 
#include <iostream>  
#include <numeric>      
using namespace std; 
   
// User defined function that returns sum of 
// arr[] using accumulate() library function. 
int arraySum(int a[], int n)  
{ 
    int initial_sum  = 0;  
    return accumulate(a, a+n, initial_sum); 
} 
   
int main()  
{ 
    int a[] = {5 , 10 , 15} ; 
    int n = sizeof(a)/sizeof(a[0]); 
    cout << arraySum(a, n); 
    return 0; 
}

輸出:

30

向量的總和



// C++ program to demonstrate working of accumulate() 
#include <iostream>  
#include <vector>  
#include <numeric>      
using namespace std; 
   
// User defined function that returns sum of 
// arr[] using accumulate() library function. 
int arraySum(vector<int> &v)  
{ 
    int initial_sum  = 0;  
    return accumulate(v.begin(), v.end(), initial_sum); 
} 
   
int main()  
{ 
    vector<int> v{5 , 10 , 15} ; 
    cout << arraySum(v); 
    return 0; 
}

輸出:

30

我們還可以使用自定義函數進行累加。在C++ STL中引用數字標頭|設置1(accumulate()和partial_sum())以獲得詳細信息。





注:本文由純淨天空篩選整理自 Array sum in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。