C++ vector 釋放記憶體的兩種方法

小麥涼發表於2018-03-31

待釋放vector: vector<valuetype> myvector

1.swap方法

vector<valuetype>().swap(myvector)

2. clear+shrink_to_fit

myvector.clear();

myvector.shrink_to_fit();

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<int> myvector;
	for (int i = 0; i < 100; i++)
	{
		myvector.push_back(i);
	}
	cout << "capacity值為:"<<myvector.capacity() << endl;
	cout << "size值為:" << myvector.size() << endl;
	myvector.clear();
	cout << "clear之後...." << endl;
	cout << "capacity值為:" << myvector.capacity() << endl;
	cout << "size值為:" << myvector.size() << endl;
	vector<int>().swap(myvector);
	cout << "swap操作後..." << endl;
	cout << "capacity值為:" << myvector.capacity() << endl;
	cout << "size值為:" << myvector.size() << endl;
	for (int i = 0; i < 100; i++)
	{
		myvector.push_back(i);
	}
	cout << "重新push_back後...." << endl;
	cout << "capacity值為:" << myvector.capacity() << endl;
	cout << "size值為:" << myvector.size() << endl;
	myvector.clear();
	myvector.shrink_to_fit();
	cout << "clear+ shrink_to_fit()後..." << endl;
	cout << "capacity值為:" << myvector.capacity() << endl;
	cout << "size值為:" << myvector.size() << endl;
	cin.get();
}

執行結果如下圖:

相關文章