Search code examples
cudathrust

thrust::device_ptr<float> has no member 'begin'


I tried to find the minimum element in an array:

 thrust::device_ptr<float> devPtr(d_ary);
 int minPos = thrust::min_element(devPtr.begin(), devPtr.end()) - devPtr.begin();

And I got the above error when compiling.

How should I fix this problem? Thanks


Solution

  • The specific error you identify is because device pointers are not containers, and therefore have no .begin() or .end() members. your devPtr is not a container, it is a device pointer usable by Thrust. You wrapped a raw pointer to create devPtr, and the raw pointer carries with it no knowledge of the size of the data region that it is pointing to.

    Pointers don't have members like begin and end.

    You could fix the problem either by:

    1. switching to using thrust vector containers which will have .begin and .end iterators defined for you
    2. manually creating begin and end pointers for the data region (d_ary) you are accessing

    Here's some example code along the lines of the latter idea above:

    #include <thrust/device_ptr.h>
    #include <thrust/extrema.h>
    
    #define N 256
    int main()
    {
    
      float *d_a;
    
      cudaMalloc((void **) &d_a, N*sizeof(float));
    
      thrust::device_ptr<float> dPbeg(d_a);
      thrust::device_ptr<float> dPend = dPbeg + N;
      thrust::device_ptr<float> result = thrust::min_element(dPbeg, dPend);
    }
    

    There is a thrust quickstart guide which may be of interest. (In the interest of clarity, I have not wrapped the cudaMalloc call with any error-checking. It's good practice to wrap cuda calls with error checking.)