Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++ STL Vector Growth Factor

📅 2010-Jul-30 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, stl, vectors ⬩ 📚 Archive

The STL vector is a dynamic array. When it grows, its internal memory is reallocated and the old values are copied over to the new space. Because of this, when the vector capacity increases the iterators, references and pointers to its elements become invalid.

The capacity increase factor of a vector depends on the STL implementation. The current capacity of a vector can be found by calling its capacity() method. By running a simple program shown below, we can figure out the factor. I found that this factor is 1.5 for Visual C++ 2010, which uses the STL implementation from Dinkumware. I also found that the factor is 2.0 on G++ 3.4.4 running under Cygwin.

using namespace std;

int main()
    vector ivec;
    for ( int i = 0; i < 1000; ++i )
        const int before = ivec.capacity();
        ivec.push_back( i );
        const int after = ivec.capacity();

        if ( before != after )
            cout << "Capacity: " << after << endl;

    return 0;