|
-
August 1st, 2010, 12:11 AM
#1
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.
-
August 1st, 2010, 12:33 AM
#2
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.
0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000 0000 0000 0000 0000
-
August 1st, 2010, 02:01 AM
#3
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.
-
August 1st, 2010, 03:17 AM
#4
Re: How to overload a matrix class?
 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
-
August 1st, 2010, 03:28 AM
#5
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|