How to overload a matrix class?
Suppose I define a class called Matrix
Code:
template <class T>
class Matrix {
......
private:
vector< vector<T> > data;
};
My question is: how to overload Matrix[i][j] which take two integers i and j as parameters?
This is an interview question that I was asked, and the interviewer precluded the way of using Matrix(i,j). Thanks a lot.
Re: How to overload a matrix class?
i would have said overloading () is not the the same as overloading [] to achieve [][]
Code:
template< typename T >
class Matrix
{
private:
vector< vector<T> > data;
public:
vector<T>& operator[]( size_t Id ){ return data[Id]; }
};
As you can see this is simple. Nothing too complicated.
Re: How to overload a matrix class?
The interviewer ask me to do the overloading so that I can use mtx[i][j] to access an element, where mtx is a Matrix object.
Obviously, you code can not do this.
Re: How to overload a matrix class?
Quote:
Originally Posted by
featips
The interviewer ask me to do the overloading so that I can use mtx[i][j] to access an element, where mtx is a Matrix object.
Obviously, you code can not do this.
First, there is no such thing as overloading operator[][]. You can only overload operator[]. Your interviewer needs to clarify the question.
Second, the code does work.
Code:
#include <vector>
template< typename T >
class Matrix
{
private:
std::vector< std::vector<T> > data;
public:
std::vector<T>& operator[]( size_t Id ){ return data[Id]; }
};
int main()
{
Matrix<int> mt;
mt[0][0] = 10;
}
This compiles with no errors.
Regards,
Paul McKenzie
Re: How to overload a matrix class?
@featips,
The code posted by Joeman is correct as far as logic is concerned. It's entirely upto you how you want to go on with it.
In a 2-D array '[]' returns the element at that index (row or column). So subsequent calls to '[]' ends
up fetching the data itself. Notice that there are no separate overloads for '[]' for 1D, 2D, 3D, etc. arrays.
Similarly the operator '[]' in case of your class can be made to return a row/column/1-D array too which with subsequent calls will finally fetch you the data.
Regards,
Nisheeth Barthwal