如何为std::vector<std::vector<TYPE>>的内层vector预留内存?
回答你的问题
Absolutely, this approach is completely valid and exactly the right way to handle your scenario! Let me break down why this works and why it's a perfect fit for your constraints:
1. Why your code works
vecs.resize(outerSize)createsouterSizeemptystd::vector<TYPE>instances. Crucially, constructing an empty vector doesn't requireTYPEto have a default constructor—since no elements are being initialized, there's no need to callTYPE()at all.- The subsequent loop calls
elem.reserve(innerSize)on each empty inner vector. This pre-allocates enough memory to hold up toinnerSizeelements ofTYPEwithout constructing anyTYPEobjects. This hits exactly what you need: it avoids the frequent small allocations that come with repeatedpush_backcalls, while respecting thatTYPEcan't be default-constructed.
2. How this fixes your original failed approach
Your initial idea of vecs.resize(outerSize, std::vector<TYPE>(innerSize)) fails because std::vector<TYPE>(innerSize) tries to create a vector with innerSize default-constructed TYPE objects—something your type doesn't support. Your revised code skips element construction entirely, focusing only on memory pre-allocation, which bypasses this restriction cleanly.
3. Key notes to remember
reserveonly sets the vector's capacity, not its size. All inner vectors will still be empty after your code runs, so you can safelypush_backoremplace_backelements as needed.- If you end up adding more than
innerSizeelements to an inner vector, it will still auto-expand as usual—but since you provided a reasonable estimate, this should happen far less often than without pre-reserving.
Concrete example
To make it tangible, if TYPE is a non-default-constructible type like this:
struct MyType { MyType(int value) : val(value) {} int val; };
Your code will work flawlessly:
std::vector<std::vector<MyType>> vecs; const size_t outerSize = 10; const size_t innerSizeEstimate = 100; vecs.resize(outerSize); for (auto& elem : vecs) { elem.reserve(innerSizeEstimate); } // Later, add elements without frequent allocations vecs[0].emplace_back(42); vecs[0].emplace_back(123); // ...
内容的提问来源于stack exchange,提问作者schorsch312
相关产品推荐
相关产品推荐

