Initial capacity of vector in C++

后端 未结 6 1599
独厮守ぢ
独厮守ぢ 2020-11-28 12:47

What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state t

6条回答
  •  眼角桃花
    2020-11-28 12:53

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

    The following code:

    #include 
    #include 
    
    int main()
    {
      using namespace std;
    
      vector 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 and:

    0
    1
    2
    3
    4
    6
    6
    9
    9
    9
    13
    

    under MSVC 2013.

提交回复
热议问题