1

我有一个自定义类myClass,它有成员weightconfig. 我想在一堆myClasses 上运行包容性扫描,但只在weights 上运行。基本上我想要的是:

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

到:

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

有没有一种简单的方法可以使用 Thrust 的精美迭代器来做到这一点?由于binaryOp需要具有关联性,因此我不知道如何仅通过重载来做到这一点operator+

4

1 回答 1

4

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} 
于 2013-06-19T23:05:49.070 回答