◆ transform_if() [2/6]

template<typename InputIterator , typename ForwardIterator , typename UnaryFunction , typename Predicate >
ForwardIterator thrust::transform_if ( InputIterator  first,
InputIterator  last,
ForwardIterator  result,
UnaryFunction  op,
Predicate  pred 

This version of transform_if conditionally applies a unary function to each element of an input sequence and stores the result in the corresponding position in an output sequence if the corresponding position in the input sequence satifies a predicate. Otherwise, the corresponding position in the output sequence is not modified.

Specifically, for each iterator i in the range [first, last) the predicate pred(*i) is evaluated. If this predicate evaluates to true, the result of op(*i) is assigned to *o, where o is the corresponding output iterator in the range [result, result + (last - first) ). Otherwise, op(*i) is not evaluated and no assignment occurs. The input and output sequences may coincide, resulting in an in-place transformation.

firstThe beginning of the input sequence.
lastThe end of the input sequence.
resultThe beginning of the output sequence.
opThe tranformation operation.
predThe predicate operation.
The end of the output sequence.
Template Parameters
InputIteratoris a model of Input Iterator, and InputIterator's value_type is convertible to Predicate's argument_type, and InputIterator's value_type is convertible to UnaryFunction's argument_type.
ForwardIteratoris a model of Forward Iterator.
UnaryFunctionis a model of Unary Function and UnaryFunction's result_type is convertible to OutputIterator's value_type.
Predicateis a model of Predicate.
first may equal result, but the range [first, last) shall not overlap the range [result, result + (last - first)) otherwise.

The following code snippet demonstrates how to use transform_if:

int data[10] = {-5, 0, 2, -3, 2, 4, 0, -1, 2, 8};
struct is_odd
__host__ __device__
bool operator()(int x)
return x % 2;
// negate odd elements
thrust::transform_if(data, data + 10, data, op, is_odd()); // in-place transformation
// data is now {5, 0, 2, 3, 2, 4, 0, 1, 2, 8};
See also