Search code examples
cudathrust

How to decrement each element of a device_vector by a constant?


I'm trying to use thrust::transform to decrement a constant value from each element of a device_vector. As you can see, the last line is incomplete. I'm trying to decrement from all elements the constant fLowestVal but dont know how exactly.

thrust::device_ptr<float> pWrapper(p);
thrust::device_vector<float> dVector(pWrapper, pWrapper + MAXX * MAXY);
float fLowestVal = *thrust::min_element(dVector.begin(), dVector.end(),thrust::minimum<float>());

// XXX What goes here?
thrust::transform(...);

Another question: Once I do my changes on the device_vector, will the changes apply also to the p array?

Thanks!


Solution

  • You can decrement a constant value from each element of a device_vector by combining for_each with a placeholder expression:

    #include <thrust/functional.h>
    ...
    using thrust::placeholders;
    thrust::for_each(vec.begin(), vec.end(), _1 -= val);
    

    The unusual _1 -= val syntax means to create an unnamed functor whose job is to decrement its first argument by val. _1 lives in the namespace thrust::placeholders, which we have access to via the using thrust::placeholders directive.

    You could also do this by combining for_each or transform with a custom functor you provided yourself, but it's more verbose.