Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
A T - student Avatar asked Mar 20 '15 20:03

A T - student


2 Answers

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.

like image 111
Mark B Avatar answered Nov 14 '22 02:11

Mark B


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
like image 40
dufresnb Avatar answered Nov 14 '22 03:11

dufresnb