You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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) creates outerSize empty std::vector<TYPE> instances. Crucially, constructing an empty vector doesn't require TYPE to have a default constructor—since no elements are being initialized, there's no need to call TYPE() at all.
  • The subsequent loop calls elem.reserve(innerSize) on each empty inner vector. This pre-allocates enough memory to hold up to innerSize elements of TYPE without constructing any TYPE objects. This hits exactly what you need: it avoids the frequent small allocations that come with repeated push_back calls, while respecting that TYPE can'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

  • reserve only sets the vector's capacity, not its size. All inner vectors will still be empty after your code runs, so you can safely push_back or emplace_back elements as needed.
  • If you end up adding more than innerSize elements 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:31:48