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 a 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); } 
  • one
    1. Use vector <int> for all array elements, not vector vectors, it will work faster and more reliably. 2. Best of all is template <int X, int Y>, and inside int _matrix [X * Y], this is the fastest option for all operations. - Arkady
  • @Arkady if the dimensions are fixed at the time of creation, std::vector is not needed at all. IMHO, the most suitable of the standard ones here is std::valarray . - αλεχολυτ
  • Yes, usually either a matrix of unclear size (then point 1), or classical 3x3 2x2 1x3, etc., and it is easier to make them template using C-arrays (point 2). - Arkady

1 answer 1

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

Use vector::resize :

 Matrix::Matrix(int dimension) : dimension(dimension), matrix(dimension) { for (auto& row : matrix) { row.resize(dimension); } }