[C ++] vector memory handling

Last week to help people do a make, implement some algorithm C ++, because for a long time did not touch the code, and the results are not a lot of vector used here to record the vector memory handling. Under normal circumstances, please do not need help vector reasonable, but when the node becomes more time, especially when drawing algorithm, you need to handle it, and to avoid drawing too much.

 clear() 

In fact, the only clear element removed, or that link these data with vector removed, and did not clean up the memory.

At this time there is a function comes in handy:

 shrink_to_fit() 

As the name suggests, it will automatically shrink to fit the size, vector after just clear is empty, after calling this function again will also clean up the memory.


Use the code to test:

    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;

You can see the final result, with the same expected (clear just change the size, did not move memory size):

 

Guess you like

Origin www.cnblogs.com/wayne-tao/p/12586158.html