thrust

◆ copy_if() [2/4]

template<typename InputIterator , typename OutputIterator , typename Predicate >
OutputIterator thrust::copy_if ( InputIterator  first,
InputIterator  last,
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 which causes pred to 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(*(first+n)). Otherwise, no assignment occurs and result is not advanced.

Parameters
firstThe beginning of the sequence from which to copy.
lastThe end of the sequence from which to copy.
resultThe beginning of the sequence into which to copy.
predThe predicate to test on every value of the range [first, last).
Returns
result + n, where n is equal to the number of times pred evaluated to true in the range [first, last).
Template Parameters
InputIteratoris a model of Input Iterator, and InputIterator's value_type is convertible to Predicate's argument_type.
OutputIteratoris a model of Output Iterator.
Predicateis a model of Predicate.
Precondition
The ranges [first, last) and [result, result + (last - first)) shall not overlap.

The following code snippet demonstrates how to use copy_if to perform stream compaction to copy even numbers to an output range.

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