Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ arrow to overloaded index ( this->[ ] )

I have a simple class, whose index operator I've overloaded:

class dgrid{
    double* data; // 1D Array holds 2D data in row-major format
  public:
    const int nx;
    const int ny;
    double* operator[] (const int index) {return &(data[index*nx]);}
}

This way dgrid[x][y] works as a 2d array, but the data is contiguous in memory.

However, from inside member functions this is a little more clunky, I need to do something like (*this)[x][y] which works, but seems smelly, especially when I have sections like:

(*this)[i][j] =   (*this)[i+1][j]
                + (*this)[i-1][j]
                + (*this)[i][j+1]
                + (*this)[i][j-1] 
                - 4*(*this)[i][j];

Is there a better way to do this? Something like this->[x][y] (but this doesn't work). Is using a little function f(x,y) returns &data[index*nx+ny] the only option?

like image 755
Samizdis Avatar asked Feb 20 '15 17:02

Samizdis


1 Answers

You could overload ->, but why not simply do:

T& that = *this; //or use auto as t.c. suggests

that[i][j] =  that[i+1][j]
            + that[i-1][j]
            + that[i][j+1]
            + that[i][j-1] 
            - 4*that[i][j];

That's (pun) at least as readable as this->[][]. No ?

like image 169
Jeffrey Avatar answered Oct 13 '22 17:10

Jeffrey