cuda thrust:选择性复制和调整结果大小

cuda thrust: selective copying and resizing results

我正在使用 copy_if 在两个推力设备阵列之间选择性地复制项目,如下所示:

thrust::device_vector<float4> collated = thrust::device_vector<float4> 
                       original_vec.size());
thrust::copy_if(original_vec.begin(), original_vec.end(),
                collated.begin(), is_valid_pt());
collated.shrink_to_fit();

is_valid_pt实现为:

struct is_valid_kpt
{
    __host__ __device__ bool operator()(const float4 x)
    {
        return x.w >= 0;
    }
}; 

现在在 运行 这段代码之后,我期望 collated 向量的大小比原始数组小得多,但它们的大小仍然相同。

Thrust 不会在任何算法调用中调整向量大小。进入推力算法的向量的大小将恰好是从算法中出来的那些向量的大小。

shrink_to_fit 对向量的 大小也没有影响,但它可能会影响与分配有关的容量。

如果要将 collated 的大小减少到复制到其中的实际元素数,则需要使用 the return value of the copy_if function 来计算其大小,然后执行调整大小。

像这样:

size_t my_size = thrust::copy_if(original_vec.begin(), original_vec.end(), collated.begin(), is_valid_pt()) - collated.begin();
collated.resize(my_size);