The product of all elements is the result of multiplying all the elements within the specified range. In this article we will learn different methods to find the product of all elements of an array in C++ using STL.
The simplest method to find the product of all elements in array is by using accumulate() method. Let’s take a look at an example:
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 2};
int n = sizeof(arr)/sizeof(arr[0]);
// Finding product of all elements
int res = accumulate(arr, arr + n,
1, multiplies<int>());
cout << res;
return 0;
}
Output
12
Explanation: By default, the accumulate() method is used to find the sum of all elements but by providing the function object multiplies gives you the product of two numbers. We use this functor with accumulate function to find the product of all elements of vector.
There are also some other methods in C++ by which we can calculate the product of all elements using STL. Some of them are as follows:
Using for_each()
The for_each() algorithm can also be used to find the product of all elements in an array by providing the lambda function in which we multiple every element of an array with variable storing the product of previous elements.
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int res = 1;
// Find product of all elements
for_each(arr, arr + n, [&res](int i) {
res *= i;
});
cout << res;
return 0;
}
Output
12
Using reduce() (C++ 17 Onwards)
The reduce() method can also be used to find the product of all elements of an array by providing the function object multiplies just like accumulate() method.
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
// Find product of all elements
int res = reduce(arr, arr + n, 1, multiplies<int>());
cout << res;
return 0;
}
Output
12