Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reserve() memory multi-dimensional std::vector (C++)

Let's we have

std::vector <std::vector <unsigned short int>> face;
face.resize(nElm);

Its OK to resize() for the first dimension. However, I also want to reserve() memory for the elements of face; I mean for the second dimension. (I am aware of the difference between resize() and reserve())

like image 846
Shibli Avatar asked Jan 29 '12 19:01

Shibli


2 Answers

Just do

face.resize(nElm);
for(auto &i : face) i.resize(nDim2);

or if you do not use c++11:

face.resize(nElm);
for(std::vector < std::vector < unsigned short int> >::iterator it
                =face.begin();it!=face.end();++it) {
   it->resize(dim2);
}

If you want to just reserve for the second dimension then just do that instead of resize

like image 54
Johan Lundberg Avatar answered Oct 02 '22 12:10

Johan Lundberg


If you want to resize it, then you need to

for(auto i=face.begin(),ie=face.end();i!=ie;++i) i->resize(nElm);

(since there's no space between two closing angle brackets, I assumed you're using c++11).

If, on the other hand, you want to reserve memory, you'd have to do it when you actually have a vector, that is — an element on the first dimension.

like image 23
Michael Krelin - hacker Avatar answered Oct 02 '22 12:10

Michael Krelin - hacker