C++: how to set the dimension of a two-dimensional vector in the class constructor

Class Matrix
{
        int dimension;
        vector<vector<int>> matrix;
    public:
        Matrix(int dimension);
        ...
}

Matrix::Matrix(int dimension)
{
    this->dimension = dimension;
}

In the Matrix::Matrix(int dimension) method, I want to set the dimension of the two-dimensional vector

dimension x dimension

But the way I did it doesn't work

matrix.reserve(dimension);
for (int i = 0; i < dimension; ++i)
{
     matrix[i].reserve(dimension);
}
Author: politician, 2015-12-21

1 answers

vector::reserve only reserves memory for elements, but does not allocate them.

Use vector::resize:

Matrix::Matrix(int dimension)
  : dimension(dimension),
    matrix(dimension)
{
    for (auto& row : matrix)
    {
        row.resize(dimension);
    }
}
 2
Author: Abyx, 2015-12-21 09:29:27