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

ผลคูณของอาร์เรย์ใน C++ ด้วย STL

นี่คือตัวอย่างโปรแกรม C++ สำหรับหาผลคูณของอาร์เรย์ (Array Product) โดยใช้ STL

อัลกอริธึม

  1. กำหนดค่าเริ่มต้นของอาร์เรย์
  2. เรียกฟังก์ชัน accumulate พร้อม multiplies<int>() เพื่อหาผลคูณ
  3. พิมพ์ผลลัพธ์

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

#include <iostream>
#include <numeric> // สำหรับ accumulate
#include <functional> // สำหรับ multiplies
using namespace std;

int ProductOfArray(int p[], int n) {
    // accumulate(begin, end, init_value, binary_op)
    // init_value = 1 (identity ของการคูณ)
    // binary_op = multiplies<int>() (ฟังก์ชันคูณ)
    return accumulate(p, p + n, 1, multiplies<int>());
}

int main() {
    int m[] = {6, 7};
    int n = sizeof(m) / sizeof(m[0]);
    cout << "Product of the Array is: " << ProductOfArray(m, n);
    return 0;
}

ผลลัพธ์

Product of the Array is: 42

คำอธิบายเพิ่มเติม:

  • accumulate อยู่ใน <numeric> ใช้สำหรับรวมค่าตามลำดับ
  • ค่าเริ่มต้น (identity) สำหรับการคูณคือ 1 สำหรับการบวกคือ 0
  • multiplies<T> เป็น function object ใน <functional> ที่ทำ operator()(a,b) { return a*b; }
  • สามารถใช้ lambda ได้: accumulate(p, p+n, 1, [](int a, int b){ return a*b; })
  • C++17 มี std::reduce สำหรับการขนาน (parallel)