C++ 11

019 使用 shrink_to_fit 要求容器退回不需要的内

2020-02-21  本文已影响0人  赵者也

在 C++ 11 新标准中,我们可以调用 shrink_to_fit 来要求 deque、vector 或 string 退回不需要的内存空间。此函数指出我们不再需要任何多余的内存空间。

使用示例:

#include <QCoreApplication>
#include <iostream>
#include <vector>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    std::vector<int> v;
    std::cout << "Default-constructed capacity is " << v.capacity() << '\n';
    v.resize(100);
    std::cout << "Capacity of a 100-element vector is " << v.capacity() << '\n';
    v.clear();
    std::cout << "Capacity after clear() is " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';

    return a.exec();
}

输出结果如下:

Default-constructed capacity is 0
Capacity of a 100-element vector is 100
Capacity after clear() is 100
Capacity after shrink_to_fit() is 0
上一篇 下一篇

猜你喜欢

热点阅读