Chinaunix首页 | 论坛 | 博客
  • 博客访问: 59163
  • 博文数量: 29
  • 博客积分: 667
  • 博客等级: 上士
  • 技术积分: 300
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-11 15:55
文章分类
文章存档

2012年(2)

2011年(27)

我的朋友
最近访客

分类: C/C++

2011-10-17 21:09:22

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;

  4. int main()
  5. {
  6.     vector<int> iVec;
  7.     cout << "size: " << iVec.size() << endl;
  8.     cout << "capacity " << iVec.capacity() << endl << endl; //1个元素, 容器容量为1

  9.     iVec.push_back(1);
  10.     cout << "size: " << iVec.size() << endl;
  11.     cout << "capacity " << iVec.capacity() << endl << endl; //2个元素, 容器容量为2

  12.     iVec.push_back(2);
  13.     cout << "size: " << iVec.size() << endl;
  14.     cout << "capacity " << iVec.capacity() << endl << endl; //3个元素, 容器容量为4

  15.     iVec.push_back(3);
  16.     cout << "size: " << iVec.size() << endl;
  17.     cout << "capacity " << iVec.capacity() << endl << endl; //4个元素, 容器容量为4

  18.     iVec.push_back(4);
  19.     iVec.push_back(5);
  20.     cout << "size: " << iVec.size() << endl;
  21.     cout << "capacity " << iVec.capacity() << endl << endl; //5个元素, 容器容量为8

  22.     iVec.push_back(6);
  23.     cout << "size: " << iVec.size() << endl;
  24.     cout << "capacity " << iVec.capacity() << endl << endl; //6个元素, 容器容量为8

  25.     iVec.push_back(7);
  26.     cout << "size: " << iVec.size() << endl;
  27.     cout << "capacity " << iVec.capacity() << endl << endl; //7个元素, 容器容量为8

  28.     iVec.push_back(8);
  29.     cout << "size: " << iVec.size() << endl;
  30.     cout << "capacity " << iVec.capacity() << endl << endl; //8个元素, 容器容量为8

  31.     iVec.push_back(9);
  32.     cout << "size: " << iVec.size() << endl;
  33.     cout << "capacity " << iVec.capacity() << endl << endl; //9个元素, 容器容量为16
  34.     /* 结论:
  35.     vector的存在可以使开发者不必关心内存的申请和释放。但是,vector背后的内存分配是按照2的倍数分配内存的。当当前容量对插入元素不够时,分配一块新的内存,这块内存的容量是原vector容量的2倍大小,然后复制旧内存,释放旧内存,可能多次涉及拷贝构造函数和析构函数,而这也正是vector的劣势所在。*/

  36.     return 0;
  37. }
阅读(534) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~