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?
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 ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With