Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D matrix and overloading operator() / ugly syntax

I'm using a 2D matrix in one of my projects. It's something like it is suggested at C++ FAQ Lite.

The neat thing is that you can use it like this:

int main()
{
  Matrix m(10,10);
  m(5,8) = 106.15;
  std::cout << m(5,8);
  ...
}

Now, I have a graph composed of vertices and each vertex has a public (just for simplicity of the example) pointer to 2D matrix like above. Now I do have a pretty ugly syntax to access it.

(*sampleVertex.some2DTable)(0,0) = 0; //bad
sampleVertex.some2DTable->operator()(0,0) = 0; //even worse...

Probably I'm missing some syntactic sugar here due to my inexperience with operator overloading. Is there a better solution?

like image 650
Nazgob Avatar asked Dec 17 '22 08:12

Nazgob


2 Answers

  1. Consider using references instead of pointers (provided, it can't be null and you can initialize in the constructor).
  2. Consider making a getter or an instance of a matrix wrapper class for a vertex that returns a reference to 2D matrix (provided, it can't be null).

    sampleVertex.some2DTable()(0,0) = 0;
    sampleVertex.some2DTableWrap(0,0) = 0;
    

However, to me it sounds like a non-issue to justify going through all the trouble.

like image 187
Alex B Avatar answered Dec 30 '22 09:12

Alex B


If you have a pointer to a Matrix, e.g. as a function parameter that you can't make a reference (legacy code, e.g.), you can still make a reference to it (pseudo code):

struct Matrix {
        void operator () (int u, int v) {
        }
};
int main () {
        Matrix *m;
        Matrix &r = *m;
        r (1,1);
}
like image 20
Sebastian Mach Avatar answered Dec 30 '22 10:12

Sebastian Mach