Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tính tổng phần tử mảng bằng STL trong C++

Sử dụng accumulate() từ header <numeric> để tính tổng mảng. Ví dụ: [12,45,74,32,66,96,21,32,27] → tổng = 405.

Ví dụ

#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);
}

Kết quả

Array is like: 12 45 74 32 66 96 21 32 27
Sum of all elements: 405