reduce in C++ STL
Last Updated :
29 Aug, 2023
The reduce() method in C++ is used for applying an algorithm to a range of elements in an array. By default, it returns the sum of values of elements in the applied range. It behaves similarly to std::accumulate in STL.
It also returns the output of the same data type as the input elements (i.e.) the data type of a single element in the array. It was introduced in C++ 17. It is defined in <numeric> header file.
Syntax
T reduce(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, T init, BinaryOp op);
Parameters
- T: type of data
- policy: Specifies the execution policy to be used for the reduction operation. It can be one of the following:
- seq: Specifies sequential execution.
- par: Specifies parallel execution.
- par_unseq: Specifies parallel execution, including vectorized execution when possible.
- first, last: Specifies the range of elements to be reduced, where first points to the first element and last points one past the last element in the range.
- init: Specifies the initial value for the reduction operation (initial value of the sum, just like in std::accumulate). It is by default 0.
- op: Specifies the binary operation to be used for the reduction. It should be a function or function object that takes two arguments of type T and returns a value of the same type T. You can write your custom function to be applied over the range of elements in the array.
Return Value
- It returns the value of the result of the reduction operation.
Example
C++
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main()
{
vector< int > v = { 1, 3, 4, 5 };
int sum = reduce(v.begin(), v.end(), 0);
cout << "Default execution of the reduce function: "
<< sum << endl;
sum = reduce(v.begin(), v.end());
cout << "Excecution with default intial value: " << sum
<< endl;
}
|
Output
Default execution of the reduce function: 13
Excecution with default intial value: 13
Time Complexity: O(N) Where N is the length of the array.
Space Complexity: O(1)
Note: If the range is empty, and init is not empty, it will return the initial value without invoking the binary operation.
Difference between std::reduce() and std::accumulate()
The biggest difference between std::accumulate and std::reduce is that std::accumulate is primarily used for sequential accumulation and requires commutative operation whereas, std::reduce is designed for parallel execution, and allows non-commutative operations.
Share your thoughts in the comments
Please Login to comment...