是否可以使用给定参数为结构创建推力函数谓词?

Is it possible to create a thrust's function predicate for structs using a given parameter?

我想使用 CUDA 的 Thrust 中的 copy_if 来压缩结构数组。 我的结构有一个 id 和一个分数。我只想复制满足最低分数的结构。阈值由用户设置。

struct is_bigger_than_threshold
{
    __host__ __device__
    bool operator()(const register x)
    {
        return (x.score > threshold);
    }
};

是的,这是可能的。仿函数需要接受结构作为其运算符参数,并且需要包含所需阈值的存储。使用仿函数时,可以将此阈值作为参数传递。这是一个完整的示例:

$ cat t688.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/copy.h>
#include <iostream>

struct my_score {

  int id;
  int score;
};

const int dsize = 10;

struct copy_func {

  int threshold;
  copy_func(int thr) : threshold(thr) {};
  __host__ __device__
  bool operator()(const my_score &x){
    return (x.score > threshold);
    }
};

int main(){

  thrust::host_vector<my_score> h_data(dsize);
  thrust::device_vector<my_score> d_result(dsize);
  int my_threshold = 50;
  for (int i = 0; i < dsize; i++){
    h_data[i].id = i;
    h_data[i].score = i * 10;}

  thrust::device_vector<my_score> d_data = h_data;

  int rsize = thrust::copy_if(d_data.begin(), d_data.end(), d_result.begin(), copy_func(my_threshold)) - d_result.begin();

  std::cout << "There were " << rsize << " entries with a score greater than " << my_threshold << std::endl;

  return 0;
}
$ nvcc -o t688 t688.cu
$ ./t688
There were 4 entries with a score greater than 50
$