Thư viện <numeric> cung cấp std::accumulate có thể tính tổng, tích, hoặc bất kỳ phép toán nhị phân nào trên dãy.
Cú pháp tính tích
accumulate(first, last, init_value, binary_op)
init_value: giá trị khởi tạo (cho tích là 1).binary_op: hàm nhị phân, dùngstd::multiplies<T>().
Ví dụ mã
#include <iostream>
#include <numeric> // accumulate, multiplies
#include <functional>
using namespace std;
int productOfArray(int arr[], int n) {
return accumulate(arr, arr + n, 1, multiplies<int>());
}
int main() {
int m[] = {6, 7};
int n = sizeof(m) / sizeof(m[0]);
cout << "Tích mảng: " << productOfArray(m, n) << endl;
return 0;
}
Kết quả
Tích mảng: 42
Lưu ý: accumulate cũng dùng cho tổng (mặc định plus<T>()), nối chuỗi, hoặc bất kỳ phép toán kết hợp nào.