Thrust

◆ transform_reduce() [1/2]

template<typename DerivedPolicy , typename InputIterator , typename UnaryFunction , typename OutputType , typename BinaryFunction >
__host__ __device__ OutputType thrust::transform_reduce ( const thrust::detail::execution_policy_base< DerivedPolicy > &  exec,
InputIterator  first,
InputIterator  last,
UnaryFunction  unary_op,
OutputType  init,
BinaryFunction  binary_op 
)

transform_reduce fuses the transform and reduce operations. transform_reduce is equivalent to performing a transformation defined by unary_op into a temporary sequence and then performing reduce on the transformed sequence. In most cases, fusing these two operations together is more efficient, since fewer memory reads and writes are required.

transform_reduce performs a reduction on the transformation of the sequence [first, last) according to unary_op. Specifically, unary_op is applied to each element of the sequence and then the result is reduced to a single value with binary_op using the initial value init. Note that the transformation unary_op is not applied to the initial value init. The order of reduction is not specified, so binary_op must be both commutative and associative.

The algorithm's execution is parallelized as determined by exec.

Parameters
execThe execution policy to use for parallelization.
firstThe beginning of the sequence.
lastThe end of the sequence.
unary_opThe function to apply to each element of the input sequence.
initThe result is initialized to this value.
binary_opThe reduction operation.
Returns
The result of the transformed reduction.
Template Parameters
DerivedPolicyThe name of the derived execution policy.
InputIteratoris a model of Input Iterator, and InputIterator's value_type is convertible to UnaryFunction's argument_type.
UnaryFunctionis a model of Unary Function, and UnaryFunction's result_type is convertible to OutputType.
OutputTypeis 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 transform_reduce to compute the maximum value of the absolute value of the elements of a range using the thrust::host execution policy for parallelization:

template<typename T>
struct absolute_value : public unary_function<T,T>
{
__host__ __device__ T operator()(const T &x) const
{
return x < T(0) ? -x : x;
}
};
...
int data[6] = {-1, 0, -2, -2, 1, -3};
data, data + 6,
absolute_value<int>(),
0,
// result == 3
See also
transform
reduce