【C++】vector的内存处理

上周帮人做了个作,用C++实现一些算法,因为好久没碰代码了,结果vector好多都不会用了,这里记录下vector的内存处理。一般情况下是不需要帮vector请理的,但是当节点变多的时候,特别是图算法的时候,就需要处理一下了,以防图太大。

 clear() 

其实clear只是把元素去掉,或者说把这些数据跟vector的链接去掉了,并没有清理内存。

这时候有个函数就有用了:

 shrink_to_fit() 

顾名思义,会自动缩减以适应大小,刚好clear之后的vector是清空的,再次调用这个函数之后就会把内存也清理。


用代码测试一下:

    std::vector<int> test_clear;
    cout << "start:\n";
    cout << test_clear.size() << endl;
    cout << test_clear.capacity() << endl;
    test_clear.push_back(10000);
    cout << "add_element:\n";
    cout << test_clear.size() << endl;
    cout << test_clear.capacity() << endl;
    test_clear.clear();
    cout << "after clear:\n";
    cout << test_clear.size() << endl;
    cout << test_clear.capacity() << endl;
    test_clear.shrink_to_fit();
    cout << "after shrink\n";
    cout << test_clear.size() << endl;
    cout << test_clear.capacity() << endl;

可以看到最终的结果,跟预想的一样(clear只是改变了size,没有动内存大小):

猜你喜欢

转载自www.cnblogs.com/wayne-tao/p/12586158.html
今日推荐