InterviewGuide
InterviewGuide copied to clipboard
c++八股文stl模板库01-20第11条:vector如何释放内存
下边代码第一行swap的作用应该是把Vec中多余的空间清除掉,相当于shrink_to_fit
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> vec (100,100); // three ints with a value of 100
vec.push_back(1);
vec.push_back(2);
cout <<"vec.size(): " << vec.size() << endl;
cout <<"vec.capasity(): " << vec.capacity() << endl;
vector<int>(vec).swap(vec); //清空vec中多余的空间,相当于vec.shrink_to_fit();
cout <<"vec.size(): " << vec.size() << endl;
cout <<"vec.capasity(): " << vec.capacity() << endl;
vector<int>().swap(vec); //清空vec的全部空间
cout <<"vec.size(): " << vec.size() << endl;
cout <<"vec.capasity(): " << vec.capacity() << endl;
return 0;
}
/*
运行结果:
vec.size(): 102
vec.capasity(): 200
vec.size(): 102
vec.capasity(): 102
vec.size(): 0
vec.capasity(): 0
*/
thanks,已做补充!