C++ – How to Initialize Vector of Vectors

c++multidimensional-arraystlvector

I am trying to use vector of vectors in C++ as a 2D array. I have to read input into it from the user. The number of rows and columns are also to be input by the user.

Supose I read m * n matrix,

I tried to allocate space using reserve(m*n) but is also giving error in building.

This is a general problem I face, I mean even in strings wherein you read char by char, how do you provide it space so you can access index i (I know it can be done using .resize(given_size)) but in situations where it is not known how many chars a user will input, this can't be done (this can be circumvented using + operator but still it is not a direct solution).

So, My primary question is how initialize the vector of vectors (not putting in values but just allocating required space, rows and columns) so that I can access [i][j] to read an value to it ?

I know that matrix can be built using vector of vectors like here but I want to first declare a vector of vectors and then take input of rows and columns to allocate space so that I can access [i][j] to input elements.

Best Answer

std::vector<std::vector<T>> my_vec(m, std::vector<T>(n))

Be careful that Ts default constructor is called for each of m * n members of the matrix.