◆ copy_if() [3/4]

template<typename DerivedPolicy , typename InputIterator1 , typename InputIterator2 , typename OutputIterator , typename Predicate >
__host__ __device__ OutputIterator thrust::copy_if ( const thrust::detail::execution_policy_base< DerivedPolicy > &  exec,
InputIterator1  first,
InputIterator1  last,
InputIterator2  stencil,
OutputIterator  result,
Predicate  pred 

This version of copy_if copies elements from the range [first,last) to a range beginning at result, except that any element whose corresponding stencil element causes pred to be false is not copied. copy_if is stable, meaning that the relative order of elements that are copied is unchanged.

More precisely, for every integer n such that 0 <= n < last-first, copy_if performs the assignment *result = *(first+n) and result is advanced one position if pred(*(stencil+n)). Otherwise, no assignment occurs and result is not advanced.

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

execThe execution policy to use for parallelization.
firstThe beginning of the sequence from which to copy.
lastThe end of the sequence from which to copy.
stencilThe beginning of the stencil sequence.
resultThe beginning of the sequence into which to copy.
predThe predicate to test on every value of the range [stencil, stencil + (last-first)).
result + n, where n is equal to the number of times pred evaluated to true in the range [stencil, stencil + (last-first)).
Template Parameters
DerivedPolicyThe name of the derived execution policy.
InputIterator1is a model of Input Iterator.
InputIterator2is a model of Input Iterator, and InputIterator2's value_type is convertible to Predicate's argument_type.
OutputIteratoris a model of Output Iterator.
Predicateis a model of Predicate.
The ranges [first, last) and [result, result + (last - first)) shall not overlap.
The ranges [stencil, stencil + (last - first)) and [result, result + (last - first)) shall not overlap.

The following code snippet demonstrates how to use copy_if to perform stream compaction to copy numbers to an output range when corresponding stencil elements are even using the thrust::host execution policy:

#include <thrust/copy.h>
struct is_even
__host__ __device__
bool operator()(const int x)
return (x % 2) == 0;
int N = 6;
int data[N] = { 0, 1, 2, 3, 4, 5};
int stencil[N] = {-2, 0, -1, 0, 1, 2};
int result[4];
thrust::copy_if(thrust::host, data, data + N, stencil, result, is_even());
// data remains = { 0, 1, 2, 3, 4, 5};
// stencil remains = {-2, 0, -1, 0, 1, 2};
// result is now { 0, 1, 3, 5}
See also