Template Function thrust::reduce(InputIterator, InputIterator, T, BinaryFunction)¶
Function Documentation¶
-
template<typename
InputIterator
, typenameT
, typenameBinaryFunction
>
Tthrust
::
reduce
(InputIterator first, InputIterator last, T init, BinaryFunction binary_op) 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 ofreduce
usesinit
as the initial value of the reduction andbinary_op
as the binary function used for summation.reduce
is similar to the C++ Standard Template Library’sstd::accumulate
. The primary difference between the two functions is thatstd::accumulate
guarantees the order of summation, whilereduce
requires associativity ofbinary_op
to parallelize the reduction.Note that
reduce
also assumes that the binary reduction operator (in this casebinary_op
) is commutative. If the reduction operator is not commutative thenthrust::reduce
should not be used. Instead, one could useinclusive_scan
(which does not require commutativity) and select the last element of the output array.The following code snippet demonstrates how to use
reduce
to compute the maximum value of a sequence of integers.- Return
The result of the reduction.
- Parameters
first
: The beginning of the input sequence.last
: The end of the input sequence.init
: The initial value.binary_op
: The binary function used to ‘sum’ values.
- Template Parameters
InputIterator
: is a model of Input Iterator andInputIterator's
value_type
is convertible toT
.T
: is a model of Assignable, and is convertible toBinaryFunction's
first_argument_type
andsecond_argument_type
.BinaryFunction
: is a model of Binary Function, andBinaryFunction's
result_type
is convertible toOutputType
.
#include <thrust/reduce.h> #include <thrust/functional.h> ... int data[6] = {1, 0, 2, 2, 1, 3}; int result = thrust::reduce(data, data + 6, -1, thrust::maximum<int>()); // result == 3
- See
- See
transform_reduce