1.原理图
实例:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; #include <vector> //巧用swap收缩空间 void test01() { vector<int> v; for (int i = 0; i < 100000; i++) { v.push_back(i); } cout << "v的容量:" << v.capacity() << endl; //13W+ cout << "v的大小:" << v.size() << endl; //10W v.resize(3); //重新分配大小 大小变了 空间还是13W+ cout << "v的容量:" << v.capacity() << endl; //13W+ cout << "v的大小:" << v.size() << endl; //3 //用swap收缩空间 vector<int>(v).swap(v); //匿名对象 拷贝构造一个临时对象 其分配了v.size()个元素的内存空间,即capacity为v.size() //然后与v交换数据, 匿名对象销毁 cout << "v的容量:" << v.capacity() << endl; //3 cout << "v的大小:" << v.size() << endl; //3 //用swap清除内存空间 vector<int>().swap(v); // 可以清除v的内存空间 cout << "v的容量:" << v.capacity() << endl; //0 cout << "v的大小:" << v.size() << endl; //0 } int main() { test01(); system("Pause"); return 0; }
结果: