Search code examples
c++vectorcudathrust

How to replace non zero values with a particular integer using CUDA library?


I want to replace all the non zero elements of a device vector with integer 1. I specifically want to use only CUDA libraries to perform this operations.

Is there any thrust function that helps me out to achieve my result?


Solution

  • Given a device vector:

    thrust::device_vector<int> X;
    

    you can use one of the thrust algorithms like this:

    thrust::transform(X.begin(), X.end(), X.begin(), [](int n) {
        return n ? 1 : 0;
    }); 
    

    or

    thrust::replace_if(X.begin(), X.end(), [](int n) {
        return n != 0;
    }, 1);