thrust::reduce
Defined in thrust/reduce.h
-
template<typename InputIterator, typename T>
T thrust::reduce(InputIterator first, InputIterator last, T init) 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.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 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 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 sum of a sequence of integers including an intialization value.#include <thrust/reduce.h> ... int data[6] = {1, 0, 2, 2, 1, 3}; int result = thrust::reduce(data, data + 6, 1); // result == 10
- Parameters
first – The beginning of the input sequence.
last – The end of the input sequence.
init – The initial value.
- Template Parameters
InputIterator – is a model of Input Iterator and if
x
andy
are objects ofInputIterator's
value_type
, thenx + y
is defined and is convertible toT
.T – is convertible to
InputIterator's
value_type
.
- Returns
The result of the reduction.