// Templated matrix class: extends vector to two dimensions // // CONSTRUCTION: with (a) no initializer (default size is 0x0) // (b) number of rows and columns // (d) another matrix (copy constructor) // // NOTE: Item type must have default constructor. // // *********************PUBLIC OPERATIONS*********************** // int rows() --> returns # of rows // int cols() --> returns # of columns // void resize(int numRows, int numCols) --> resizes matrix // operator[] --> returns row of matrix // operator<< --> outputs to a stream ////////////////////////////////////////////////////////////////// #ifndef _MATRIX_H #define _MATRIX_H #include #include using namespace std; template class Matrix { public: Matrix(int rows = 0, int cols = 0) // postcondition: matrix w/ dimensions rows x cols constructed { resize(rows, cols); } void resize(int newRows, int newCols) { numRows = newRows; numCols = newCols; mat.resize(numRows); for(int k=0; k < numRows; k++) { mat[k].resize(numCols); } } int rows() const // row capacity of matrix { return numRows; } int cols() const // column capacity of matrix { return numCols; } vector & operator[](int index) { return mat[index]; } const vector & operator[](int index) const { return mat[index]; } friend ostream & operator<<(ostream & ostr, const Matrix & Rhs) { for (int r = 0; r < Rhs.rows(); r++) { for (int c = 0; c < Rhs.cols(); c++) { ostr << Rhs.mat[r][c] << " "; } ostr << endl; } return ostr; } private: vector< vector > mat; // the matrix of items int numRows; // # of rows (capacity) int numCols; // # of cols (capacity) }; #endif