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

หาผลรวมอาร์เรย์ด้วย C++ STL

วิธีการหาผลรวมอาร์เรย์

1. วิธีคลาสสิก (Loop ธรรมดา)

#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 << "Array sum: " << sum; // 39
    return 0;
}

2. ใช้ std::accumulate (แนะนำ) - ต้อง include <numeric>

#include <iostream>
#include <numeric> // สำคัญ!
using namespace std;

int main() {
    int arr[] = {2, 5, 7, 8, 2, 6, 9};
    int n = 7;
    
    // รูปแบบ: accumulate(begin, end, initial_value)
    int sum = accumulate(arr, arr + n, 0);
    
    cout << "Array sum: " << sum; // 39
    return 0;
}

3. ใช้กับ std::vector

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main() {
    vector<int> v = {12, 56, 76, 2, 90, 3};
    
    // ใช้ iterator
    int sum = accumulate(v.begin(), v.end(), 0);
    
    cout << "Vector sum: " << sum; // 239
    return 0;
}

4. ใช้กับข้อมูลชนิดอื่น (double, long long)

vector<double> prices = {19.99, 29.50, 9.99};
double total = accumulate(prices.begin(), prices.end(), 0.0); // 0.0 สำคัญ!

vector<long long> bigNumbers = {10000000000LL, 20000000000LL};
long long total = accumulate(bigNumbers.begin(), bigNumbers.end(), 0LL);

5. ใช้ Custom Binary Operation

#include <functional> // สำหรับ multiplies

// คูณทุกตัวแทนที่จะบวก
int product = accumulate(arr, arr + n, 1, multiplies<int>());

// หรือใช้ lambda
int sumOfSquares = accumulate(arr, arr + n, 0, 
    [](int acc, int x) { return acc + x * x; });

สรุป

  • accumulate เป็นมาตรฐาน STL ที่ควรใช้
  • รองรับทุก container ที่มี iterator
  • ระวังชนิดค่าเริ่มต้น (initial value) ต้องตรงกับชนิดข้อมูล
  • สามารถปรับพฤติกรรมได้ด้วย binary operation ตัวที่ 4