// // demonstrates a vector of vectors // allocates a vector of vectors, and for each element in the vector, allocates a vector of integers // // // Written by Maxwell Sayles, 2001, for CPSC331, University of Calgary. // #include #include using namespace std; // // demonstrates a vector of vectors // 'data' is a vector of vectors // for each element in data, we allocate another vector of integers // class Matrix { public: Matrix (int rows, int columns); ~Matrix(); int getRowCount() { return this->rows; } int getColumnCount() { return this->columns; } int getItem (int row, int column); void setItem (int row, int column, int value); private: int** data; int rows; int columns; }; // // construct the matrix // allocate a vector of vectors to integers // for each element in the vector, allocate another vector of integers // Matrix::Matrix (int rows, int columns) { this->rows = rows; this->columns = columns; this->data = new int*[rows]; // allocate vector of vectors (meaning, allocate an array of pointers, so a pointer to pointers) for (int i = 0; i < rows; i = i + 1) { // for each element in above, allocate a vector integers this->data[i] = new int[columns]; } } // // destruct // delete each vector integers // then delete the vector of vectors // Matrix::~Matrix() { for (int i = 0; i < this->rows; i = i + 1) { delete[] this->data[i]; } delete[] this->data; } // // retrieve an item from the matrix // int Matrix::getItem (int row, int column) { int* columnVector = this->data[row]; return columnVector[column]; // can be shortened to // return this->data[row][column]; } // // set an item in the matrix // void Matrix::setItem (int row, int column, int value) { int* columnVector = this->data[row]; columnVector[column] = value; // can be shortened to // this->data[row][column] = value; } // // program entry // int main() { // construct a matrix Matrix m (16, 18); int c = 0; int r = 0; // fill out matrix with multiplication table for (c = 0; c < m.getColumnCount(); c = c + 1) { for (r = 0; r < m.getRowCount(); r = r + 1) { m.setItem (r, c, c*r); } } // print indexes along columns cout << " x "; for (c = 0; c < m.getColumnCount(); c = c + 1) { // similar to cout, only this will print decimal values right aligned to four digits cout << setw(3) << c << ' '; } cout << endl << endl; // print matrix for (r = 0; r < m.getRowCount(); r = r + 1) { cout << setw(2) << r << ' '; for (c = 0; c < m.getColumnCount(); c = c + 1) { int value = m.getItem (r, c); cout << setw(3) << value << ' '; } cout << endl; } cout << endl; return 0; }