Search code examples
c++thrust

Thrust : how could i fill an array by range with index and range


I try to fill an array by range using index and values

   thrust::device_vector<int> vec(12) 
    vec[1] = 2;
    vec[6] = 3;
    vec[10] = 1;

the result should be

vec { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0}

instead i have

vec { 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0}

does some could tell where i'm wrong ? Thanks

Here my code :

#include <thrust/device_vector.h>
#include <thrust/scan.h>
#include <iterator>

template<class T>
struct FillRange
{
    __host__ __device__ T operator()(const T& res, const T& dat)
    {
        return dat >= T(0)  ? dat : 1;
    }
};

int main()
{
    thrust::device_vector<int> vec(12);
    vec[1] = 2;
    vec[6] = 3;
    vec[10] = 2;

    thrust::inclusive_scan(
            vec.rbegin(), vec.rend(),
            vec.rbegin(),
            FillRange<int>());

    thrust::copy(
            vec.begin(), vec.end(),
            std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}

Solution

  • Here the code for the expected result.

    The array give index and the number of flag to be set: so for

       thrust::device_vector<int> vec(12) 
        vec[1] = 2;
        vec[6] = 3;
        vec[10] = 1;
    

    the result will be

    vec { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0}
    
    #include <thrust/device_vector.h>
    #include <thrust/scan.h>
    #include <iterator>
    
    
    struct clean_
    {
        __host__ __device__ 
        int operator()(const int &p1) const
        {
            return (p1>0)?1:p1;
        }
    };
    
    template<class T>
    struct FillRange
    {
        __host__ __device__ T operator()(const T& res, const T& dat)
        {
            return ((res-1)>0)? res-1 : dat ;
        }
    };
    
    int main()
    {
        thrust::device_vector<int> vec(12);
        vec[1] = 2;
        vec[6]  = 3;
        vec[11] = 2;
    
        thrust::inclusive_scan(
                vec.begin(), vec.end(),
                vec.begin(),
                FillRange<int>());
    
        thrust::transform(
                vec.begin(), 
                  vec.end(),
                vec.begin(),
                clean_());
    
        thrust::copy(
                vec.begin(), vec.end(),
                std::ostream_iterator<int>(std::cout, " "));
        std::cout << std::endl;
    }