【C++】vector的記憶體處理
阿新 • • 發佈:2020-12-13
先上結論,對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:\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,沒有動記憶體大小):