2013-06-19 52 views
0

我有一個自定義班級myClass其成員weightconfig。我想對一堆myClass es進行全面掃描,但僅限於weight s。基本上我想要的是採取:只有一個班級成員的推力掃描

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

到:

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

有一個簡單的方法來做到這一點使用推力的幻想迭代器?由於binaryOp需要聯想,我不知道如何做到這一點,只是超載operator+

+0

你並不需要使用花哨的迭代器。只需創建一個函子,它需要兩個'myClass'參數並返回它們的'weight's的總和並將其傳遞給'inclusive_scan'。 –

+0

'inclusive_scan'知道將矢量中'myClass'的'weight'設置爲我的仿函數將返回的'double'嗎? – limes

回答

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}