Suppose the following data structure typedef std::vector<std::vector<int> > MYARRAY
is defined. Then for the variable MYARRAY var
, how can I allocate memory for this variable before pushing data in it. For example,
std::vector<int> p1;
p1.push_back(1);
p1.push_back(2);
std::vector<int> p2;
p2.push_back(22);
p2.push_back(33);
var.push_back(p1);
var.push_back(p2);
If we do not allocate memory for var
, then it will allocate memory automatically. So how can I allocate memory for this var before pushing data insider it? If it is std::vector<int> var2
, I can just use var2.reserve(n)
to allocate memory before using it.
EDIT: Two suggestions have been made, but neither can work:
- Solution 1: allocate memory for each element
var.reserve(3); for(int i=0; i<3; i++) var[i].reserve[20];
I use VC 2010 to compile and run the codes in the debug mode, and the following error message is given:
Solution 2: create the object in the beginning
std::vector<std::vector<int> > var(3, std::vector<int>(5));
After you created this variable, you can see this variable in VC 2010:
Its contents are already there. Therefore, if you push data on this variable, it will allocate memory once again.
EDIT 2:
Someone is interested in why I need allocate memory before using this variable, and the main reason is because of run-time library of windows. The variable var
is defined in a executable program as an empty variable, and its contents are given by a function defined in a dynamic library. If both are using dynamic run-time library, it will not be an issue. But in my case both are linked with static run-time library, which means that each module is in charge of its memory allocation. Since var
is defined in the executable program, it also should take care of its memory allocation.