从 device_vector 中删除元素

Gao*_*uan 5 cuda thrust

推力::device_vector 值

推力::device_vector 键;

初始化后,keys包含一些等于-1的元素。我想删除键中和值相同位置的元素。

但不知道并行如何处理?

Rob*_*lla 5

可能有很多方法可以做到这一点。一种可能的方式:

  1. thrust::remove_if使用(文档)的模板版本,将键作为模板,删除值中相应键为-1的元素。您将需要为谓词测试创建一个函子。
  2. 在键上使用thrust::remove文档)来删除 -1 的值

这是一个例子:

#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/remove.h>
#include <thrust/sequence.h>

#define N 12
typedef thrust::device_vector<int>::iterator dintiter;

struct is_minus_one
{
  __host__ __device__
  bool operator()(const int x)
  {
    return (x == -1);
  }
};

int main(){

  thrust::device_vector<int> keys(N);
  thrust::device_vector<int> values(N);

  thrust::sequence(keys.begin(), keys.end());
  thrust::sequence(values.begin(), values.end());

  keys[3] = -1;
  keys[9] = -1;

  dintiter nve = thrust::remove_if(values.begin(), values.end(), keys.begin(), is_minus_one());
  dintiter nke = thrust::remove(keys.begin(), keys.end(), -1);

  std::cout << "results  values:" << std::endl;
  thrust::copy(values.begin(), nve, std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl << "results keys:" << std::endl;
  thrust::copy(keys.begin(), nke, std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl;

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

  • 另一种方法是仅使用“remove_if”并将“keys”和“values”数组压缩在一起。给“remove_if”的谓词将检查元组的第一个元素是否有感兴趣的键。这可能会快一点,因为键数组的元素只需要加载一次。 (2认同)