場合によります。
最終的なサイズがわからない場合は、その割り当てスキームを使用してベクターを割り当てます (通常は毎回 2 倍にするか、そのあたりのどこかで)。このようにして、すべての要素の再割り当てを回避します。
std::vector<int> v;
// good:
for (/* populate v */) // unknown number of iterations
{
v.push_back(i); // possible reallocation, but not often
}
// bad:
for (/* populate v */) // unknown number of iterations
{
v.reserve(v.size() + 1); // definite reallocation, every time
v.push_back(i); // (no reallocation)
}
ただし、事前に再割り当てしないことがわかっている場合は、事前に割り当てます。
std::vector<int> v;
// good:
v.reserve(10);
for (/* populate v */) // only 10 iterations (for example)
{
v.push_back(i); // no reallocations
}
// not bad, but not the best:
for (/* populate v */) // only 10 iterations (for example)
{
v.push_back(i); // possible reallocation, but not often (but more than needed!)
}