Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาผลรวมสมาชิกอาร์เรย์ด้วย STL accumulate() ใน C++

ใช้ฟังก์ชัน accumulate() จาก header <numeric> คำนวณผลรวมองค์ประกอบในอาร์เรย์หรือคอนเทนเนอร์

รูปแบบ

accumulate(first, last, init) → คืนค่า init + ผลรวมของ [first, last)

ตัวอย่างโค้ด

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

    return 0;
}

ผลลัพธ์

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

การใช้งานขั้นสูง

// ผลคูณแทนผลบวก
#include 
accumulate(arr, arr + n, 1, multiplies());

// สตริง concat
vector v = {"a", "b", "c"};
accumulate(v.begin(), v.end(), string("")); // "abc"

// ใช้ Lambda
accumulate(arr, arr + n, 0, [](int a, int b){ return a + b*b; }); // ผลรวมกำลังสอง