待释放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();
}
运行结果如下图:
原文链接:https://blog.csdn.net/weixin_39690551/article/details/79770344