Perhaps if you say what you mean you wouldn't get people answering what you wrote.
Your matrix needs to dynamically allocate to store its members.
The best way to do this is not to be two-dimensional but to be single-dimensional in its allocation. You need M * N elements so allocate M*N in one go.
To find element( i, j ), it is actually element ( i * M ) + j.
Thus you have something like, if the elements are double
class Matrix
{
private:
double * m_mem;
size_t m_width;
size_t m_height;
public:
Matrix( size_t width, size_t height );
~Matrix();
double operator()( size_t i, size_t j ) const
{
return m_mem[ i * m_width + j ];
}
double& operator()( size_t i, size_t j )
{
return m_mem[ i * m_width + j ];
}
size_t width() const
{
return m_width;
}
size_t height() const
{
return m_height;
}
Matrix(Matrix const& other ); // you implement
Matrix& operator=( Matrix const& other ); // you implement
};
- You will want 2 overloads for operator(), a non-const one for setting these members.
- You might wish to bounds check.
Allocate thus:
Matrix::Matrix( size_t width, size_t height ) :
m_mem( new double[width * height] ),
m_width( width ),
m_height( height )
{
}
Free thus:
Matrix::~Matrix()
{
delete [] m_mem;
}
You will need to manage the copying and assigning, given the rule of 3.
It is not possible to deallocate part of your matrix.
If you want to make the Matrix generic, you must write a template. But I don't know if you have yet learnt how to write templates.
For addition and subtraction, you could use class members or:
Matrix operator+( Matrix const& left, Matrix const& right )
{
assert( left.width == right.width );
assert( left.height == right.height );
Matrix sum( left.width, left.height );
for( size_t i = 0; i < left.width; ++i )
{
for( size_t j = 0; j < left.height; ++j )
{
sum( i, j ) = left( i, j ) + right( i, j );
}
}
return sum; // in C++11 return std::move(sum) and return-type Matrix&&
}
If you used class members (or make the operator a friend) you can make use of your internal structure by running through every element in the one-dimensional arrays in a single (rather than nested) loop. It won't improve the complexity of the algorithm which is still height * width, although it may be a tiny bit faster due to the pointer arithmetic.