#include <iostream>
#include <vector>
#include <string>
using namespace std;
void print_size(vector<int> &);
int main()
{
vector<int> ivec(4);
cout<<"size为当前元素数量、capacity为当前空间总量\n";
print_size(ivec);
ivec.push_back(0);
print_size(ivec);
while(ivec.size()!=ivec.capacity())
ivec.push_back(0);
ivec.push_back(0);
print_size(ivec);
cout<<"可看出每当容器必须分配空间时,它加倍当前容量\n";
//测试reserve\resize
ivec.resize(0);
print_size(ivec);
cout<<"可看出resize清空了所有元素,空间总量没变\n";
ivec.reserve(50);
print_size(ivec);
cout<<"可看出reserve设置了空间总量\n";
//装满容器
while(ivec.size()!=ivec.capacity())
ivec.push_back(0);
print_size(ivec);
cout<<"装满容器后并没有重新分配空间\n我们再加一个元素上去\n";
ivec.push_back(0);
print_size(ivec);
cout<<"重复刚才的过程\n";
while(ivec.size()!=ivec.capacity())
ivec.push_back(0);
ivec.push_back(0);
print_size(ivec);
cout<<"\n\n最后reserve并不是定义了一种分配策略"
<<"\n而是定义了当前的空间总量" <<endl;
return 0;
}
void print_size(vector<int> &ivec)
{
cout<<"size: " <<ivec.size()
<<" capacity: " <<ivec.capacity()
<<endl;
}
欢迎光临 新微赢技术网 (http://bbs.weiying.cn/) | Powered by Discuz! X3.2 |