I've hit a road block with a certain project of mine. I want to create an Upper Triangle Matrix (all elements below the diagonal are zero) that allocates only the memory necessary to hold the nonzero elements. The problem that I'm having is indexing into this matrix. I would rather not have to redesign the matrix, but if that is the only solution, then I can accept it. As a side note, the Vector is my own implementation, not the stl Vector.
So far I have the class declared as follows:
template <class T>
class UMatrix : public AbstractMatrix<T>
{
private:
Vector<T>* m_data;
int m_size;
public:
//lots of member functions
};
The constructor of the Upper Triangle Matrix:
template <class T>
UMatrix<T>(const int size)
{
m_size = size;
if(size < 1)
throw(RangeErr(size));
m_data = new Vector<T> [size];
for(int i = 0; i < size; i++)
{
Vector<T> init(i + 1);
m_data[i] = init;
}
}
And the code that I'm having trouble with:
template <class T>
Vector<T>& operator[] (const int index)
{
if(m_data != NULL && index >= 0 && index < m_rows)
{
// Insert dark magic here
}
else
{
throw(RangeErr(index));
}
}
This results in an array of staggered vectors, each vector being 1 length larger than the previous.
I am attempting to implement the bracket operator such that UMatrix[a][b]
accesses row a, column b of the true Upper Triangular Matrix. This means that UMatrix[a][b] == 0
when a > b
.
The bracket operator is also a virtual function from the abstract base class, and must return a Vector&. Also, this implementation must use the bracket operator, not the function () operator, so that it is compatible with previously written code. I am aware that it would be simpler to use a dense matrix, but I am limited to only necessary memory usage.
My first attempt involved using one vector for storage, similar to a 1d array matrix. However, the bracket operator is also seemingly impossible to write for that implementation as well.
My question: is it even possible to implement this bracket operator?
The professor changed the project specifications to allow for the parenthesis operator overload. This is the best method available to solve this problem.