推力:基于另一个矢量的选择性复制



我想使用一组推力操作来选择性地将一个矢量A的元素复制到基于第三个矢量C中元素的谓词的新矢量B中。

这里有一个例子:当B中对应的元素是1C时,我想从A复制元素(按顺序),如果它是0,就不要。如果B中有0,我想要|C| < |A|。我们可以通过缩减B来预先确定C的大小。例句:

A = [2, 3, 6, 0, 11]

B = [1, 0, 1, 1, 0]

C = [2, 6, 0]

任何帮助都是非常感谢的

这种算法被称为流压缩。在thrust::copy_if中实现。

下面的例子摘自Thrust文档。

#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(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}

尽管Abator已经给了function使用的权利。让我试一个完整的例子。

//~~~START:Wed, 06-Oct-2021, 21:41:22 IST
//~~~Author:Rajesh Pandian M | mrprajesh.co.in
//~~CompiledWith: nvcc a.cu -std=c++14 --expt-extended-lambda
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <stdio.h>
int main(void) {
const int N=5;
int A[]={2, 3, 6, 0, 11}; //Data
int B[]={1, 0, 1, 1, 0 }; //Stencil
thrust::device_vector<int> dA(A, A + N);
thrust::device_vector<int> dB(B, B + N);
// Allocates memory based on #number of 1's
thrust::device_vector<int> dC(thrust::count(B, B+N,1));
//Condition on the stencil elements. If 1 is seen copy, else do not!
thrust::copy_if( dA.begin()
,dA.end()
,dB.begin()
,dC.begin()
,[] __host__ __device__ (const int& x){
return 1 == x;
});
//Prints
thrust::for_each(dC.begin(), dC.end(),
[] __host__ __device__(const int& x){ printf("%d ",x);});
return 0;
}

最新更新