How to change from using pointer to vector inside the class
My teacher wants me to change from using a pointer to vector in order to create a 1D array matrix with a 1D vector. At first, I try by changing double *_data; to vector<double> _data; but it doesn't work since I didn't really understand the problem (._.) Here is the code #include <iostream> #include <cassert> using namespace std; class cmatrix { public: cmatrix(unsigned int numRows, unsigned int numCols) { _data = new double[numRows * numCols]; _cols = numCols; _rows = numRows; for (unsigned int i = 0; i < rows(); i = i + 1) { for (unsigned int j = 0; j < cols(); j = j + 1) { setElement(i, j, 0.0); } } } ~cmatrix() { delete[] _data; } double element(unsigned int row, unsigned int col) { assert(row < rows() && col < cols()); return _data[row * cols() + col]; } unsigned int rows() { return _rows; } unsigned int cols() { return _cols; } void setElement(unsigned int row, unsigned int col, double value) { assert(row < rows() && col < cols()); _data[row * cols() + col] = value; } private: unsigned int _cols; unsigned int _rows; double *_data; }; int main() { cmatrix m(5, 5); for (unsigned int i = 0; i < m.rows(); i = i + 1) { m.setElement(i, i, 1.0); // m._data[i * m.cols() + i] = 1.0; } for (unsigned int i = 0; i < m.rows(); i = i + 1) { for (unsigned int j = 0; j < m.cols(); j = j + 1) { cout << m.element(i, j) << " "; } cout << endl; } return 0; } Output: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1