预备知识:
1.为了使vector容器实现快速的内存分配,其实际分配的容量要比当前所需的空间多一些;vector预留了这些额外的存储区,用于存放新添加的元素。
2.容器的capacity(容量)与size(长度)的区别:size指容器当前拥有的元素个数;capacity指容器在必须分配新存储空间之前可以存储的元素总数。
3.reverse操作告诉vector容器应该预留多少元素的存储空间。
程序清单:
#include <iostream>
#include <vector>
using namespace std;
int main(int argc,char *argv[])
{
/*空vector容器的size为0,capacity也为0*/
vector<int> ivec;
cout << "The size of ivec is: " << ivec.size() <<endl
<< "The capacity of ivec is: " << ivec.capacity() <<endl;
/*give ivec 25 elements*/
/*当在vector中插入元素时,容器的size就是所添加的元素个数,而其capacity
必须至少等于size,但通常比size值更大*/
for(vector<int>::size_type ix=0; ix!=25; ++ix)
{
ivec.push_back(ix);
}
cout << "The size of ivec is: " << ivec.size() << endl
<< "The capacity of ivec is: " << ivec.capacity() <<endl;
/*set capacity to at least 50;might be more*/
ivec.reserve(50); //预留50个元素的存储空间
cout << "The size of ivec is: " << ivec.size() << endl
<< "The capacity of ivec is: " << ivec.capacity() << endl;
/*add elements to use up the excess capacity*/
/*只使用了预留的容量,vector没做任何内存分配工作,所以capacity不变*/
while(ivec.size() != ivec.capacity())
{
ivec.push_back(0);
}
cout << "The size of ivec: " << ivec.size() << endl
<< "The capacity of ivec: " << ivec.capacity() << endl;
/*add one more element*/
/*如果预留的容量已耗尽,再添加新的元素,vector必须为自己重新分配存储空间*/
/*每当vector容器不得不分配新的存储空间时,以加倍当前容量的分配策略实现重新分配*/
ivec.push_back(51);
cout << "The size of ivec: " << ivec.size() << endl
<< "The capacity of ivec: " << ivec.capacity() << endl;
return 0;
}
|
程序执行结果:
obe-240 /home/eagle> g++ -o capacity capacity.cpp
obe-240 /home/eagle> ./capacity
The size of ivec is: 0
The capacity of ivec is: 0
The size of ivec is: 25
The capacity of ivec is: 32
The size of ivec is: 25
The capacity of ivec is: 50
The size of ivec: 50
The capacity of ivec: 50
The size of ivec: 51
The capacity of ivec: 100
阅读(7040) | 评论(0) | 转发(0) |