A simple matrix class

This class enables you to say:

Matrix<int> mymat(10,20);
//...
mymat(2,4) = 49;
int x = mymat (5,3);
//...

and so on for a 2 dimensional array of any object you like (not just int).

Put this code at the top of your program (or in a header file):

// A skeletal matrix template class.
template <class T> class Matrix {
public:         
        unsigned nx, ny;
        T* data;
        
        Matrix(unsigned nx_in, unsigned ny_in)
        : nx(nx_in), ny(ny_in), data(new T[nx_in*ny_in]) {}
        
        ~Matrix() { delete[] data; }
        
        // copy ctor
        Matrix(const Matrix& m) {
                nx = m.nx; ny = m.ny;
                data = new T[m.nx * m.ny];
        }
        
        // assign
        Matrix& operator=(const Matrix& m) {
                if (this != &m) {
                        delete[] data;
                        nx = m.nx; ny = m.ny;
                        data = new T[nx*ny];
                        for(unsigned i=0; i<nx*ny; i++) data[i] = m.data[i];
                }
                return *this;
        }
        
        T& operator() (unsigned x, unsigned y) {
                //assert(x<nx_ && y<ny_);
                return data[x*ny + y];
        }
        
        T& operator() (unsigned x, unsigned y) const {
                //assert(x<nx_ && y<ny_);
                return data[x*ny + y];
        }
};

M.S.Colclough, Sep 2005