# Another Question on implementing a matrix

• 06-10-2011
manasij7479
Another Question on implementing a matrix
I learnt here about a month ago that plain arrays are the best when making a matrix class(as opposed to linked lists ..etc...as I had a whim to do !!).

Which one of the following would be a better idea when I'd have to make the matrices do almost all sorts of operations and transformations..within my knowledge..?
Code:

```template<class X,int R,int C> //Type,No of Rows and Columns class matrix {     public:     typedef std::array<X,C> row_a;     //Size of a row == no. of cols     std::array<row_a,R> dat; };```
OR
Code:

```template<class X,int R,int C> //Type,No of Rows and Coloumns class matrix {     public:     std::array<X,(R*C)> dat; };```
If the former is better ....what is the way to access the individual X objects ..with iterators...?
• 06-10-2011
brewbuck
Quote:

If the former is better ....what is the way to access the individual X objects ..with iterators...?
Why not just brackets?

Code:

`matrix[j][i]`
The reason for creating such types is not to inflict terrible syntax on everyone.
• 06-10-2011
manasij7479
Would a 1d array respond same to matrix[i][j] compared to a array declared in a 2d fashion?
• 06-10-2011
brewbuck
Quote:

Originally Posted by manasij7479
Would a 1d array respond same to matrix[i][j] compared to a array declared in a 2d fashion?

No, but the solution to the problem isn't difficult. The j,i'th element (row j, column i) is located at index "j*C+i" (C is your "number of columns" constant).

You could use an operator such as:

Code:

`X &operator()(int row, int col) { return dat[row*C + col]; }`
Then you address the matrix as mat(j, i)
• 06-10-2011
manasij7479
..Thank You..
<finally> What is the difference between *your piece of code and
Code:

`X operator()(int row, int col) { return *( dat[row*C+col] ); }`
?
• 06-10-2011
brewbuck
Quote:

Originally Posted by manasij7479
..Thank You..
<finally> What is the difference between *your piece of code and
Code:

`X operator()(int row, int col) { return *( dat[row*C+col] ); }`
?

The above code is incorrect, because you can't apply the dereferencing "*" operator to an array element (well, if it was a pointer you could, but the result would not be of type X). The reason I made the return type a reference is so that you can assign to the matrix by writing:

Code:

`mat(j, i) = val;`