Initial capacity of vector in C++

后端 未结 6 1601
独厮守ぢ
独厮守ぢ 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:56

    Standard doesnt specify initial value for capacity but the STL container automatically grows to accomodate as much data as you put in, provided you don't exceed the maximum size(use max_size member function to know). For vector and string, growth is handled by realloc whenever more space is needed. Suppose you'd like to create a vector holding value 1-1000. Without using reserve, the code will typically result in between 2 and 18 reallocations during following loop:

    vector v;
    for ( int i = 1; i <= 1000; i++) v.push_back(i);
    

    Modifying the code to use reserve might result in 0 allocations during the loop:

    vector v;
    v.reserve(1000);
    
    for ( int i = 1; i <= 1000; i++) v.push_back(i);
    

    Roughly to say, vector and string capacities grow by a factor of between 1.5 and 2 each time.

提交回复
热议问题