只扫描一个班级成员的推力扫描

时间:2013-06-19 19:31:16

标签: cuda thrust

我有一个自定义班级myClass,其成员有weightconfig。我想对一堆myClass es进行包容性扫描,但只能在weight s上进行。基本上我想要的是:

[ {configA, weightA}, {configB, weightB}, {configC, weightC}, ...]

为:

[ {configA, weightA}, {configB, weight A + weightB}, {configC, weight A + weight B + weightC}, ...]

使用Thrust的花式迭代器有一种简单的方法吗?由于binaryOp必须是关联的,因此我不会看到如何只重载operator+

1 个答案:

答案 0 :(得分:3)

inclusive_scan需要一个关联运算符,但它不需要是可交换的。如果您创建一个二进制函数,将其第二个参数的配置成员复制到结果中,它应该可以解决:

#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/scan.h>

struct my_struct
{
  __host__ __device__
  my_struct() {}

  __host__ __device__
  my_struct(const my_struct &other)
    : config(other.config), weight(other.weight)
  {}

  __host__ __device__
  my_struct(char c, double w)
    : config(c), weight(w)
  {}

  char config;
  double weight;
};


struct functor
{
  __host__ __device__
  my_struct operator()(my_struct a, my_struct b)
  {
    my_struct result;
    result.config = b.config;
    result.weight = a.weight + b.weight;
    return result;
  }
};

int main()
{
  thrust::device_vector<my_struct> vec(3);

  vec[0] = my_struct('a', 1);
  vec[1] = my_struct('b', 2);
  vec[2] = my_struct('c', 3);

  std::cout << "input: ";
  for(int i = 0; i < vec.size(); ++i)
  {
    my_struct x = vec[i];
    std::cout << "{" << x.config << ", " << x.weight << "} ";
  }
  std::cout << std::endl;

  thrust::inclusive_scan(vec.begin(), vec.end(), vec.begin(), functor());

  std::cout << "result: ";
  for(int i = 0; i < vec.size(); ++i)
  {
    my_struct x = vec[i];
    std::cout << "{" << x.config << ", " << x.weight << "} ";
  }
  std::cout << std::endl;

  return 0;
}

输出:

$ nvcc -arch=sm_20 test.cu -run
input: {a, 1} {b, 2} {c, 3} 
result: {a, 1} {b, 3} {c, 6}