zoukankan      html  css  js  c++  java
  • 【C++】vector的内存处理

    先上结论,对vector的内存处理需要两步:

    1 std::vector<int> test_clear;
    2 test_clear.clear();
    3 test_clear.shrink_to_fit();

    分析:

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

     clear() 

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

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

     shrink_to_fit() 

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


    验证:

    用代码测试一下:

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

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

  • 相关阅读:
    gulp
    grunt
    iscroll手册
    Javascript闭包演示【转】
    【转】Backbone.js学习笔记(二)细说MVC
    【转】Backbone.js学习笔记(一)
    node包管理相关
    写出高效率的正则表达式的几点建议
    常用正则表达式
    help、man和info工具的区别
  • 原文地址:https://www.cnblogs.com/wayne-tao/p/12586158.html
Copyright © 2011-2022 走看看