Open In App

reduce in C++ STL

Last Updated : 29 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to illustrate the use of reduce() function
#include <iostream>
#include <numeric>
#include <vector>
  
using namespace std;
  
int main()
{
    vector<int> v = { 1, 3, 4, 5 };
  
    // reduce returns sum of the elements in the given range
    int sum = reduce(v.begin(), v.end(), 0);
    cout << "Default execution of the reduce function: "
         << sum << endl;
  
    // here it returns the sum without needing to pass the
    // intial value
    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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads