使用道具 举报
#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; }
本版积分规则 发表回复 回帖后跳转到最后一页
申请友链|小黑屋|最新主题|手机版|新微赢技术网 ( 苏ICP备08020429号 )
GMT+8, 2024-11-19 11:31 , Processed in 0.124946 second(s), 10 queries , Gzip On, Memcache On.
Powered by xuexi
© 2001-2013 HaiAn.Com.Cn Inc. 寰耽