How can I resize a 2D C++ vector?
c++, resize, vector
Solution
Given the vector is empty, you can simply resize the outer vector with preallocated inner vectors without the need of a loop:
matrix.resize(ROW, vector<char>(COL));
Alternatively, when initializing or if you want to reset a non-empty vector, you can use the constructor overload taking a size and initial value to initialize all the inner vectors:
matrix = vector<vector<char> >(ROW, vector<char>(COL));
I assumed you access it with `matrix[row][col]`. In C++ matrices are usually stored in row-major order. If you wanted column-major order, you need to swap the arguments `ROW` and `COL`.
Problem
I have a 2D `char` vector: ``` vector< vector<char> > matrix; ``` I will read in a matrix as an input and store it in that vector. The size of my vector is fixed and is ROW x COL. I guess I need to resize it for each row and column. How can I accomplish it without taking extra memory (resizing it correctly)?