如何使用 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
廣告