Reserve () memory multidimensional std :: vector (C ++)

May we have

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

Its ok up to resize()for the first dimension. However, I also want reserve()memory for face elements; I mean the second dimension. (I know the difference between resize()and reserve())

+5
source share
3 answers

Just do

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

or if you are not using 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 just reservefor the second dimension, just do it insteadresize

+4
source

If you want to resize it, you need to

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

(since there is no space between the two closing brackets, I assumed that you are using c++11).

, , , , , .

+2

You will need to skip the first dimension and resize the second, either using iterators, or simply:

for (int i=0; i<nElm; i++) {
    face[i].resize(nElm2ndDimension);
}
+1
source

All Articles