thrust

◆ reduce() [6/6]

template<typename InputIterator , typename T , typename BinaryFunction >
T thrust::reduce ( InputIterator  first,
InputIterator  last,
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 of reduce uses init as the initial value of the reduction and binary_op as the binary function used for summation. 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 binary_op to parallelize the reduction.

Note that reduce also assumes that the binary reduction operator (in this case binary_op) 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.

Parameters
firstThe beginning of the input sequence.
lastThe end of the input sequence.
initThe initial value.
binary_opThe binary function used to 'sum' values.
Returns
The result of the reduction.
Template Parameters
InputIteratoris a model of Input Iterator and InputIterator's value_type is convertible to T.
Tis a model of Assignable, and is convertible to BinaryFunction's first_argument_type and second_argument_type.
BinaryFunctionis a model of Binary Function, and BinaryFunction's result_type is convertible to OutputType.

The following code snippet demonstrates how to use reduce to compute the maximum value of a sequence of integers.

#include <thrust/reduce.h>
...
int data[6] = {1, 0, 2, 2, 1, 3};
int result = thrust::reduce(data, data + 6,
-1,
// result == 3
See also
http://www.sgi.com/tech/stl/accumulate.html
transform_reduce