Search code examples
c++vectorthrust

Vector initialization in thrust


I am new with C++ and I want to have a vector with rational step size in thrust library. I wrote these code and it gives me an error when I am trying to define vector A as a pointer. I would be thankful if some could tell me what's wrong with my code.

void Vector_Initialize (thrust::host_vector<double> *A, double lb, double delta)
{
    for (int i = 0; i < A.size(); i++)
        A[i]  = lb + i * delta;
}
int main()
{
    thrust::host_vector<double> h_V(10);
    //thrust::sequence(h_V.begin(), h_V.end(), 20, 0.4);
    double lb=20, delta=0.4;
    Vector_Initialize(h_V, lb, delta);
    for (int i = 0; i < 10; i++)
    {
        std::cout<<h_V[i]<<std::endl;
    }
    std::cout<< "size of vector is" << h_V.size()<<std::endl;
    return 0;

}

here is error :

Error   1   error : expression must have class type H:\...\kernel.cu    16  1   CUDATUt13
Error   2   error : no operator "=" matches these operands  H:\...\kernel.cu    17  1   CUDATUt13
Error   3   error : identifier "$h_V" is undefined  H:\....\kernel.cu   24  1   CUDATUt13

Solution

  • void Vector_Initialize (thrust::host_vector<double> *A, double lb, double delta)
    

    should be replaced with

    void Vector_Initialize (thrust::host_vector<double> &A, double lb, double delta)
    

    *A means A is a pointer (may be to one vector or an array or vectors). &A means A is a reference.

    If you still want to stick with *A (not recommended), replace

    for (int i = 0; i < A.size(); i++)
        A[i]  = lb + i * delta;
    

    with

    for (int i = 0; i < A->size(); i++)
        (*A)[i]  = lb + i * delta;
    

    and pass the address of h_V to Vector_Initialize function.