reduce
is a generalization of summation: it computes the sum (or some other binary operation) of all the elements in the range [first, last)
. This version of reduce
uses 0
as the initial value of the reduction. reduce
is similar to the C++ Standard Template Library's std::accumulate
. The primary difference between the two functions is that std::accumulate
guarantees the order of summation, while reduce
requires associativity of the binary operation to parallelize the reduction.
Note that reduce
also assumes that the binary reduction operator (in this case operator+) is commutative. If the reduction operator is not commutative then thrust::reduce
should not be used. Instead, one could use inclusive_scan
(which does not require commutativity) and select the last element of the output array.
The algorithm's execution is parallelized as determined by exec
.
- Parameters
-
exec | The execution policy to use for parallelization. |
first | The beginning of the sequence. |
last | The end of the sequence. |
- Returns
- The result of the reduction.
- Template Parameters
-
DerivedPolicy | The name of the derived execution policy. |
InputIterator | is a model of Input Iterator and if x and y are objects of InputIterator's value_type , then x + y is defined and is convertible to InputIterator's value_type . If T is InputIterator's value_type , then T(0) is defined. |
The following code snippet demonstrates how to use reduce
to compute the sum of a sequence of integers using the thrust::host
execution policy for parallelization:
...
int data[6] = {1, 0, 2, 2, 1, 3};
- See also
- https://en.cppreference.com/w/cpp/algorithm/accumulate