นี่คือตัวอย่างโปรแกรม C++ สำหรับหาผลคูณของอาร์เรย์ (Array Product) โดยใช้ STL
อัลกอริธึม
- กำหนดค่าเริ่มต้นของอาร์เรย์
- เรียกฟังก์ชัน
accumulateพร้อมmultiplies<int>()เพื่อหาผลคูณ - พิมพ์ผลลัพธ์
โค้ดตัวอย่าง
#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)