According to the following test, it seems that a std::vector<int>
increases its capacity in this way:
it happens when we
push_back()
and the capacity is already full (i.e.v.size() == v.capacity()
), it has to be noted that it doesn't happen a little bit beforethe capacity increases to 1.5 times the previous capacity
Question: why this 1.5 factor? Is it implementation-dependent? Is it optimal?
Also, is there a way to analyze, in this code, when exactly a reallocation happens? (sometimes maybe the capacity can be increased without moving the first part of the array)
vector<int> v;
int previouscapacity = 0;
for (unsigned int i = 0; i < 1000000; i++)
{
v.push_back(i);
if (v.capacity() != previouscapacity)
{
wcout << L"new capacity: " << v.capacity() << L" new size: " << v.size() << L" ratio: " << ((float) v.capacity()) / previouscapacity << '\n';
previouscapacity = v.capacity();
}
}
new capacity: 1 new size: 1 ratio: 1.#INF
new capacity: 2 new size: 2 ratio: 2
new capacity: 3 new size: 3 ratio: 1.5
new capacity: 4 new size: 4 ratio: 1.33333
new capacity: 6 new size: 5 ratio: 1.5
new capacity: 9 new size: 7 ratio: 1.5
new capacity: 13 new size: 10 ratio: 1.44444
new capacity: 19 new size: 14 ratio: 1.46154
new capacity: 28 new size: 20 ratio: 1.47368
new capacity: 42 new size: 29 ratio: 1.5
new capacity: 63 new size: 43 ratio: 1.5
new capacity: 94 new size: 64 ratio: 1.49206
new capacity: 141 new size: 95 ratio: 1.5
new capacity: 211 new size: 142 ratio: 1.49645
...
new capacity: 466609 new size: 311074 ratio: 1.5
new capacity: 699913 new size: 466610 ratio: 1.5
new capacity: 1049869 new size: 699914 ratio: 1.5
Note: I'm using VC++ 2013