As a side project I'm writing a couple of classes to do matrix operations and operations on linear systems. The class LinearSystem
holds pointers to Matrix
class objects in a std::map
. The Matrix
class itself holds the 2d array ("matrix") in a double float pointer. To I wrote 2 overloaded [ ] operators, one to return a pointer to a matrix object directly from the LinearSystem
object, and another to return a row (float *) from a matrix object.
Both of these operators work perfectly on their own. I'm able to use LinearSystem["keyString"]
to get a matrix object pointer from the map. And I'm able to use Matrix[row]
to get a row (float *) and Matrix[row][col]
to get a specific float element from a matrix objects' 2d array.
The trouble comes when I put them together. My limited understanding (rising senior CompSci major) tells me that I should have no problem using LinearSystem["keyString"][row][col]
to get an element from a specific array within the Linear system object. The return types should look like LinearSystem->Matrix->float *->float. But for some reason it only works when I place an extra [0] after the overloaded key operator so the call looks like this: LinearSystem["keyString"][0][row][col]
. And it HAS to be 0, anything else and I segfault.
Another interesting thing to note is that CLion sees ["keyString"]
as overloaded and [row]
as overloaded, but not [0]
, as if its calling the standard index operator, but on what is the question that has me puzzled. LinearSystem["keyString"] is for sure returning Matrix *
which only has an overloaded [ ] operator. See the attached screenshot.
Here's the code, let me know if more is needed.
LinearSystem [ ] and map declaration:
Matrix *myNameSpace::LinearSystem::operator[](const std::string &name) {
return matrices[name];
}
std::map<std::string, Matrix *> matrices;
Matrix [ ] and array declaration:
inline float *myNameSpace::Matrix::operator[](const int row) {
return elements[row];
}
float **elements;
Note, the above function is inline'd because I'm challenging myself to make the code as fast as possible and even with compiler optimizations, the overloaded [ ] was 15% to 30% slower than using Matrix.elements[row]
.
Please let me know if any more info is needed, this is my first post so it I'm sure its not perfect.
Thank you!