我想做的是在向量上创建一个过滤器,以便它删除未通过谓词测试的元素;但不太确定我该怎么做。
我根据谓词评估输入向量中的每个元素,例如在我的代码中,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;
}
最佳答案
在 stream compaction group 内你可能对 thrust::copy_if
我们可以使用您定义的谓词直接将偶数元素选择到新向量中,而无需制作中间 filter
向量:
thrust::copy_if(col1.begin(), col1.end(), result.begin(), is_even<int>());
(result
应该是一个与col1
类型相同的向量,并且已经定义为等于或大于col1
的长度,因为不知道有多少元素会通过谓词测试。)
如果您想处理您创建的filter
向量,请使用stencil version 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
$
关于cuda - 推力收集/过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20071454/