简体   繁体   中英

Using the Thrust library for CUDA for an array reduction

I am using thrust to find the sum of an array ,c, but I keep getting compiler error "error: expresion must have class type"

float tot = thrust::reduce(c.begin(), c.end());

This is the code line that isn't working, c is a float array and is the element sum of 2 other arrays.

Cheers

It is possible to pass pointers to thrust::reduce . If you have a pointer to an array in host memory, you can do something like this:

float tot = thrust::reduce(c, c + N); // N is the length of c in words

If your pointer is to an array in device memory, you need to cast it as a thrust::device_ptr first:

thrust::device_ptr<float> cptr = thrust::device_pointer_cast(c);
float tot = thrust::reduce(cptr, cptr + N); // N is the length of c in words

c应该是thrust类型,例如thrust::host_vectorthrust::device_vector

There's an example for thrust::reduce on the Thrust github page . You can't call .begin() on a plain old array since it's not an instance of an object, ie it's meaningless. As an example, it'd be like calling .begin() on the array "b" in the code below.

int main(void)
{
    thrust::host_vector<float> a(10);
    float b[10];

    thrust::fill(a.begin(), a.end(), 1.0);
    thrust::fill(b, b+10, 2.0);

    cout << "a: " << thrust::reduce(a.begin(), a.end()) << endl;
    cout << "b: " << thrust::reduce(b, b+10) << endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM