Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the capacity of std::vector determined

Tags:

c++

stdvector

I know that in std::vector, the size will grow every time it runs out of room. Yet I'm not noticing a pattern in how it grows. Can someone please explain to me the pattern and why it was chosen.

#include <iostream>
using namespace std;

#include <iostream>
#include <vector>
int main()
{
    vector<int> myVector;
    for(int i =0 ; i < 100; ++i)
    {
        myVector.push_back(i);
        cout << myVector.capacity();
    cout << ", ";
    }
}

Result:

1, 2, 3, 4, 6, 6, 9, 9, 9, 13, 13, 13, 13, 19, 19, 19, 19, 19, 19, 28, 28, 28, 2
8, 28, 28, 28, 28, 28, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 6
3, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 6
3, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 9
4, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 141, 141, 141, 141, 141, 141
like image 943
Caesar Avatar asked Jan 28 '26 11:01

Caesar


2 Answers

It depends on the implementation, so don't expect the same pattern when you switch the operating system, the compiler, etc.

The most common growth patterns are 1.5 * previous_capacity and 2 * previous_capacity. In your example, it seems that it's the former.

See https://stackoverflow.com/a/1100426/784668 for a possible explanation for why that factor was chosen. The point is that it apparently allows reusing free memory blocks that were previously used for storing the array.

It is an implementation detail, you are not supposed co care about it. In your case it seems to be something like

i += i/2

but somewhat more complex.

like image 20
yuri kilochek Avatar answered Jan 31 '26 01:01

yuri kilochek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!