Search code examples
vectorcudathrust

How to copy values from uint2 to one vector in thrust?


I am having values in vector<uint2> results (size) I just wanna copy the values of results.y alone to a vector<int> count (size). How can I do this using thrust::transform function?


Solution

  • You need to declare some kind of function object (it can be either UnaryFunction or BinaryFunction that will select second element from uint2. You can use lambda if you enable --expt-extended-lambda in nvcc:

    auto selector = [&] __device__ (const uint2& pair) { return pair.y; };

    You can use function object instead:

    struct Selector
    {
        __host__ __device__ unsigned int operator()(const uint2& pair) 
        {
            return pair.y;
        }
    };
    

    And then use it in thrust::transform:

    thrust::transform(results.begin(), results.end(), count.begin(), selector);

    or

    Selector selectorObject;
    thrust::transform(results.begin(), results.end(), count.begin(), selectorObject);