A T - student
A T - student

Reputation: 292

C++ vector reduce allocation size

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.

Upvotes: 5

Views: 891

Answers (3)

Sergey
Sergey

Reputation: 1590

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

Upvotes: 0

dufresnb
dufresnb

Reputation: 135

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

Upvotes: 2

Mark B
Mark B

Reputation: 96311

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.

Upvotes: 7

Related Questions