swap 去除vector多余的容量
2015-12-22 22:28
267 查看
#include "stdafx.h" #include <vector> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<char> tempBufferVec(10); cout<<tempBufferVec.size ()<<endl;//10 cout<<tempBufferVec.capacity ()<<endl<<endl;//10 vector<char>(tempBufferVec).swap(tempBufferVec); cout<<tempBufferVec.size ()<<endl;//10 cout<<tempBufferVec.capacity ()<<endl<<endl;//10 tempBufferVec.reserve (20); cout<<tempBufferVec.size ()<<endl;//10 cout<<tempBufferVec.capacity ()<<endl<<endl;//20 vector<char>(tempBufferVec).swap(tempBufferVec); cout<<tempBufferVec.size ()<<endl;//10 cout<<tempBufferVec.capacity ()<<endl<<endl;//10 return 0; }
即;
先创建一个临时拷贝与原先的vector一致,值得注意的是,此时的拷贝 其容量是尽可能小的符合所需数据的。紧接着将该拷贝与原先的vector 进行 交换。执行交换后,临时变量会被销毁,内存得到释放。此时的v即为原先
的临时拷贝,而交换后的临时拷贝则为容量非常大的vector(不过已经被销毁)
相关文章推荐
- Ceph 多节点quick部署
- 第二章 一切都是对象
- 宣化上人:这四句偈能治眼睛的病
- 固定于底部的图片返回按钮
- JVM生命周期和类加载机制
- Community detection
- MySQL GTID复制
- LA 3644 (并查集)
- The Apache Tomcat Native library which allows optimal performance in production environments was not
- java项目怎么加包而不是引用
- 在Docker中部署Subversion 1.9.3(CentOS7)
- 理解Java的类和对象
- 3.操作系统一些基本理念
- 结构体数组
- 软件工程之四则运算--Github
- <li><ol><ul>
- 杭电-5596
- Effective Objective-C 2.0 学习笔记---(一)
- 应用层
- 40个Java多线程问题总结(优就业JAVA分享)