Search code examples
c++operator-overloadingsparse-matrix

Allow modification of only non-zero elements of a sparse matrix


I am implementing a tridiagonal matrix and I have to be as efficient as possible. Obviously I will only hold the elements that contain data. I overloaded the operator() to act as an indexer into the matrix, but I want this operator to return a reference so that the user can modify the matrix. However, I cannot just return 0; for the non-tridiagonal elements since the zero is not a reference. How do I let the user modify the data on the tridiagonal, but when the operator() is used to inspect a non-tridiagonal element, only return 0 instead of a reference to 0?

below is the related class definition

template <class T>
class tridiagonal
{
  public:
    tridiagonal();
    ~tridiagonal();
    T& operator()(int i, int j);
    const T& operator()(int i, int j) const; 

  private:
    //holds data of just the diagonals
    T * m_upper;
    T * m_main;
    T * m_lower;
};

Solution

  • The issue you have here is an inappropriate interface. If your definition of a matrix is a 2D array of numbers such that every element of the matrix can be individually set, then a sparse, tridiagional matrix is paradoxically not a matrix (just as a square is not a modifiable rectangle - a classic example of inappropriate inheritance that doesn't obey the Liskov Substitution Principle).

    In short, you'd be better off changing your interface to suit sparse, tridiagonal matrices rather than trying to hack it to work with the interface you've got. That said, if you must do it this way, then you are probably better off doing two things:

    • Modifying your const accessor to return T instead of const T& (I'm assuming we're only dealing with matrices of numbers here). Then you can just return 0 for the elements off the diagonal.
    • Modifying your non-const accessor to return a reference to a dummy element for locations off the diagonal, and crossing your fingers :) Alternatively, you could change the specification to throw in such cases, but that might be a little unfriendly.

    One other alternative (short of reworking the interface properly) might be to return proxy objects instead of Ts. The proxy for dummy elements would then throw when you try and set the value using it.