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}