C ++向量减少了分配大小

时间:2015-03-20 20:24:35

标签: c++ memory-management

C ++向量何时在实践中动态减少其分配的大小。

我知道分配的空间会在插入完整向量时加倍,但是当分配减少时我不清楚。经典的滞后是在从1/4满矢量中移除时将分配大小减半。

3 个答案:

答案 0 :(得分:7)

在没有明确指示的情况下,它永远不会缩小已分配的内存。

在C ++ 11中,有一个shrink_to_fit调用将要求实现执行此操作,但它可能不会减少分配的内存。在以前的版本中,您必须创建一个新副本并交换旧副本。

答案 1 :(得分:2)

至少在我的编译器中,向量似乎没有减少它们分配的空间。 我跑的时候:

        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;
        }

返回的是:

    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

答案 2 :(得分:0)

Befor C ++ 11你可以通过为它赋予一个新值来清空向量:

vector<int> x;
x.resize(500);
x = vector<int>(); // assigning a copy of new empty vector will shrink memory usage