5

When does a C++ vector dynamically reduce its allocated size in practice.

I know that the allocated space doubles upon an insert into a full vector, but it's not clear to me when the allocation is reduced. The classical hysteresis is to halve the allocation size upon removal from a 1/4-full vector.

A T - student
  • 212
  • 1
  • 12
  • 1
    The standard does not mandate the capacity to double upon reallocation. It only implies that the growth must be geometric to achieve amortized constant time insertion. But any growth factor α > 1 will qualify for that. – 5gon12eder Mar 20 '15 at 20:39

3 Answers3

7

It will never shrink the allocated memory in the absence of explicit direction to do so.

In C++11 there is a shrink_to_fit call that will ask the implementation to do this, but it may not reduce the allocated memory. In prior versions you have to create a new copy and swap away the old one.

Mark B
  • 95,107
  • 10
  • 109
  • 188
2

At least in my compiler, vectors do not appear to reduce their allocated space. When I run:

        std::vector<int> v;
        for(unsigned x=0;x<20;++x)
        {
            v.push_back(x);
            out << "elements: " << v.size() << ", capacity: " << v.capacity() << std::endl;
        }
        for(unsigned x=v.size();x>0;--x)
        {
            v.pop_back();
            out << "elements: " << v.size() << ", capacity: " << v.capacity() << std::endl;
        }

What is returned is:

    elements: 1, capacity: 1
    elements: 2, capacity: 2
    elements: 3, capacity: 4
    elements: 4, capacity: 4
    elements: 5, capacity: 8
    elements: 6, capacity: 8
    elements: 7, capacity: 8
    elements: 8, capacity: 8
    elements: 9, capacity: 16
    elements: 10, capacity: 16
    elements: 11, capacity: 16
    elements: 12, capacity: 16
    elements: 13, capacity: 16
    elements: 14, capacity: 16
    elements: 15, capacity: 16
    elements: 16, capacity: 16
    elements: 17, capacity: 32
    elements: 18, capacity: 32
    elements: 19, capacity: 32
    elements: 20, capacity: 32
    elements: 19, capacity: 32
    elements: 18, capacity: 32
    elements: 17, capacity: 32
    elements: 16, capacity: 32
    elements: 15, capacity: 32
    elements: 14, capacity: 32
    elements: 13, capacity: 32
    elements: 12, capacity: 32
    elements: 11, capacity: 32
    elements: 10, capacity: 32
    elements: 9, capacity: 32
    elements: 8, capacity: 32
    elements: 7, capacity: 32
    elements: 6, capacity: 32
    elements: 5, capacity: 32
    elements: 4, capacity: 32
    elements: 3, capacity: 32
    elements: 2, capacity: 32
    elements: 1, capacity: 32
    elements: 0, capacity: 32
dufresnb
  • 135
  • 10
0

Befor C++11 you could empty vector by assigning it a new value:

vector<int> x;
x.resize(500);
x = vector<int>(); // assigning a copy of new empty vector will shrink memory usage
Sergey
  • 1,552
  • 20
  • 18