#include <vector>
using namespace std;
int main()
{
vector<int> resizeVect;
vector<int> reserveVect;
resizeVect.resize(50, 2); //立即分配50个int,每个值为2,默认值为0,如果是class默认构造函数
vector<int>::iterator iter = resizeVect.begin();
printf("out put resizeVect value start\n");
for(; iter != resizeVect.end(); iter++)
{
printf("%d ", *iter);
}
printf("\nout put resizeVect value end\n");
printf("resizeVect capacity %d \n", resizeVect.capacity());
printf("resizeVect size %d \n", resizeVect.size());
resizeVect.push_back(3); //添加一个值后,超出了capacity,capacity增加一半
printf("resizeVect capacity %d \n", resizeVect.capacity());
printf("resizeVect size %d \n", resizeVect.size());
printf("\r\n \r\n");
reserveVect.reserve(50); //预留capacity为50,但是没有内存,当然也不会有值
iter = reserveVect.begin();
printf("out put resizeVect value start\n");
for(; iter != reserveVect.end(); iter++)
{
printf("%d ", *iter);
}
printf("\nout put resizeVect value end\n");
printf("reserveVect capacity %d \n", reserveVect.capacity());
printf("reserveVect size %d \n", reserveVect.size());
reserveVect.push_back(3); //添加一个值后,没有超出capacity,capacity保持不变,size+1
printf("reserveVect capacity %d \n", reserveVect.capacity());
printf("reserveVect size %d \n", reserveVect.size());
system("pause");
return 1;
}
vector中resize和reserve的区别,代码验证
最新推荐文章于 2020-11-01 11:22:26 发布