vector容器resize和reserve方法的区别
程序员文章站
2022-03-21 19:53:48
...
vector可以理解为,可以自动扩容的数组。但是因为数据在堆上,所以每次扩容需要经历,申请内存,拷贝数据,释放内存的过程。
vector提供两个方法,resize和reverse方法。resize执行扩容操作并且自动执行构造函数。reverse仅仅修改容量大小,及vector的capacity的大小。vector的clear方法,仅仅修改有效数据数量,不回收内存。
cout<<"veValuesOne resize"<<endl;
vector<int> veValuesOne;
cout<<"size:"<<veValuesOne.size() <<" cap:"<<veValuesOne.capacity()<<endl;
veValuesOne.resize(10);
cout<<"size:"<<veValuesOne.size() <<" cap:"<<veValuesOne.capacity()<<endl;
cout<<veValuesOne.at(5)<<endl;
cout<<"veValuesTwo reserve"<<endl;
vector<int> veValuesTwo;
cout<<"size:"<<veValuesTwo.size() <<" cap:"<<veValuesTwo.capacity()<<endl;
veValuesTwo.reserve(10);
cout<<"size:"<<veValuesTwo.size() <<" cap:"<<veValuesTwo.capacity()<<endl;
//cout<<veValuesTwo.at(5)<<endl;//宕机
cout<<"veValuesThree clear"<<endl;
vector<int> veValuesThree;
veValuesThree.push_back(10);
cout<<"size:"<<veValuesThree.size() <<" cap:"<<veValuesThree.capacity()<<endl;
veValuesThree.clear();
cout<<"size:"<<veValuesThree.size() <<" cap:"<<veValuesThree.capacity()<<endl;