简体   繁体   中英

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() )

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

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.

You'll have to loop through the first dimension and resize the second, either using iterators or a simple;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM