Initial capacity of vector in C++

Storage implementations of std::vector vary significantly, but all the ones I've come across start from 0.

The following code:

#include <iostream>
#include <vector>

int main()
{
  using namespace std;
  
  vector<int> normal;
  cout << normal.capacity() << endl;
  
  for (unsigned int loop = 0; loop != 10; ++loop)
  {
      normal.push_back(1);
      cout << normal.capacity() << endl;
  }
  
  cin.get();
  return 0;
}

Gives the following output:

0
1
2
4
4
8
8
8
8
16
16

under GCC 5.1, 11.2 - Clang 12.0.1 and:

0
1
2
3
4
6
6
9
9
9
13

under MSVC 2013.


The standard doesn't specify what the initial capacity of a container should be, so you're relying on the implementation. A common implementation will start the capacity at zero, but there's no guarantee. On the other hand there's no way to better your strategy of std::vector<int> iv; iv.reserve(2345); so stick with it.