Generally, if the vector is stored in the pointer, you must first traverse again, release the pointer points to memory. (If the element vector is built-in type, then there is no need to do this step)
and then release the memory occupied by each element in the vector, which can be used when swap method.
Note, Clear function simply remove the element, does not release memory.
Look at the following code:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<double>it;
double a[100000];
for(int i=0;i<100000;i++)
{
a[i]=i;
}
cout << "未放元素时容器大小为: " << it.size() << "容器容量为: " << it.capacity() << endl; //未放元素
for(int i=0;i<100000;i++)
{
it.push_back(a[i]);
}
cout << "放元素后容器大小为: " << it.size() << "容器容量为: " << it.capacity() << endl; //放元素
it.clear();
cout << "clear后容器大小为: " << it.size() << "容器容量为: " << it.capacity() << endl; //clear
vector<double>().swap(it);
cout << "swap后容器大小为: " << it.size() << "容器容量为: " << it.capacity() << endl; //swap
return 0;
}
operation result: