推力收集/过滤

use*_*422 2 cuda thrust

我想要做的是在向量上创建一个过滤器,以便删除不通过谓词测试的元素; 但我不太确定如何去做.

我根据谓词评估我的inputer向量中的每个元素,例如我的代码中的is_even函数,在device_vector向量中.如果通过测试则确实如此,如果不通过则为假.

现在我被卡住,因为我现在有这个bool向量,我想收集通过这个谓词测试的元素.我将它存储在bool向量中,因为我想保留结果以过滤其他向量.

#include ...

template<typename T>
struct is_even : thrust::unary_function<T, bool>
{
    __host__ __device__
    bool operator()(const T &x)
    {
        return (x%2)==0;
    }
};

int main(void)
{
    std::cout << "Loading test!" << std::endl;
    const int N = 1000000;
    thrust::device_vector<int> col1(N);
    thrust::device_vector<float> col2(N, 1); 
    thrust::sequence(col1.begin(), col1.end());

    thrust::device_vector<bool> filter(N);
    thrust::transform(col1.begin(), col1.end(), filter.begin(), is_even<int>());

    // filter col1 and col2 based on filter

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*lla 5

您可能感兴趣的流压缩组thrust::copy_if

我们可以使用您定义的谓词直接在偶数元素中选择偶数元素,而无需制作中间filter向量:

thrust::copy_if(col1.begin(), col1.end(), result.begin(), is_even<int>());
Run Code Online (Sandbox Code Playgroud)

(result应该是一个相同类型的向量col1,并且已经定义为长度等于或大于col1,因为未知有多少元素将通过谓词测试.)

如果你想关闭的工作filter你已经创建载体,应用的模板版本copy_if替代.

这是一个基于您的评论使用模板方法的工作示例:

$ cat t267.cu
#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/sequence.h>
#include <thrust/transform.h>
#include <thrust/copy.h>

template<typename T>
struct is_even : thrust::unary_function<T, bool>
{
    __host__ __device__
    bool operator()(const T &x)
    {
        return (x%2)==0;
    }
};


struct is_true : thrust::unary_function<bool, bool>
{
    __host__ __device__
    bool operator()(const bool &x)
    {
        return x;
    }
};

int main(void)
{
    std::cout << "Loading test!" << std::endl;
    const int N = 1000000;
    thrust::device_vector<int> col1(N);
    thrust::device_vector<float> col2(N, 1);
    thrust::sequence(col1.begin(), col1.end());

    thrust::device_vector<bool> filter(N);
    thrust::device_vector<int> result(N);
    thrust::transform(col1.begin(), col1.end(), filter.begin(), is_even<int>());
    // filter col1 based on filter
    thrust::device_vector<int>::iterator end = thrust::copy_if(col1.begin(), col1.end(), filter.begin(), result.begin(), is_true());
    int len = end - result.begin();
    thrust::host_vector<int> h_result(len);
    thrust::copy_n(result.begin(), len, h_result.begin());
    thrust::copy_n(h_result.begin(), 10, std::ostream_iterator<int>(std::cout, "\n"));


    return 0;
}
$ nvcc -arch=sm_20 -o t267 t267.cu
$ ./t267
Loading test!
0
2
4
6
8
10
12
14
16
18
$
Run Code Online (Sandbox Code Playgroud)