Search code examples
c++operator-overloadingthrust

overload operator [ ] to enable element assignment


I've already overloaded operator [ ] to enable element access.

definition

double Matrix::operator[ ](const & int i){
     return data[i]; // data[] is a member array: thrust:: device_vector
}

usage

Matrix m = ... // initialize
std::cout << m[3] << std::endl;

But now I want to access element by index so that assign new value to it.

usage

m[3] = 0.;   

I understand the return value of the operator overload function must be an lvalue. I guess I should return a reference, but not sure how this is done. Thanks!

EDIT

Now I changed my definition to double &, but it still complains:

 error: initial value of reference to non-const must be an lvalue

The array refers to a thrust::device_vector, which can be assigned value by index:

Thrust::device_vector<double> M(10);
M[3] = 0.;

Solution

  • Just replace

    double ....

    with

    double& .....