Overloading operator []
-
13-10-2019 - |
Question
I have a task to write a class matrix in C++ and there is a condition, to override the operator [] for matrix so if I have a matrix with name Matrix with this "Matrix[0][0]" I must take it's first element, on it's first line. I have represented the matrix with two dimensional dynamic array and templates (T **matrix). Could you help me, please?
PS: This method I'm using to create the two dimensional array:
template <class T>
T ** Matrix<T>::createMatrix(unsigned int rows, unsigned int cols)
{
T** matrix = new T*[rows];
for (unsigned int i = 0; i < rows; i++) {
matrix[i] = new T[cols];
}
return matrix;
}
Solution
i assume matrix is a member variable of type T** of Matrix.
template< class T >
T* operator []( Matrix<T>& m, unsigned int row )
{
// maybe remember rows and assert(row<rows);
return m.matrix[ row ];
}
Now you may write something like
Matrix<T> m(50,9999);
m[42][1337];
to access element 1337 in row 42.
OTHER TIPS
You can do this with two classes. The matrix class overrides [] and returns a row object. The row object overrides [] and returns a scalar.
What you want to do is return a T* in operator[], as it can then have operator[] applied to it natively and get the result that you want. However, I want to point out that it's pretty bad practice to leave your pointers raw.
You can't do that natively in C++, but you could simply instanciate your matrix this way:
Matrix<Matrix<int>> m;
This way the first [ ] returns another matrix which will return the item you want. Of course a much better name for your class then would be Vector, and a wrapper class called Matrix that creates an internal Vector<Vector<T>>
.
The method you are using to create the matrix doesn't have anything to do with a class, as your requirements state. You are creating a simple T**
, it doesn't make a difference that you are doing it in a class method.
Creating a matrix of T
that can be used as in matrix[i][j]
means that the expression matrix[i]
must return a type on which operator []
is also defined to return a T
. Therefore, the usual way to do it is break it down in steps:
Matrix<T> operator[] (int)
returns aMatrixRow<T>&
MatrixRow<T>& operator[] (int)
returns aT&
There will also be const
versions of these operators to be used when reading values from the matrix (non-const versions will be used when writing to the matrix).
So, at the minimum, you should create a class with this interface:
template <typename T>
class Matrix {
public:
Matrix(int rows, int cols);
const MatrixRow<T>& operator[] (int row) const;
MatrixRow<T>& operator[] (int row);
}
PS: This reads like a homework question, is it one?