vector容器成员函数resize与reserve的区别
resize是设置向量的大小:即向量的大小与容量相同。而reserve是设置向量的容量,并不改变向量的大小。另外:向量的最大大小是固定住,不可改变。例子:#include"stdafx.h"#include#include using namespace std; typedefvectorint> VEC_INT;int_tmain(int ar
resize是设置向量的大小:即向量的大小与容量相同。而reserve是设置向量的容量,并不改变向量的大小。另外:向量的最大大小是固定住,不可改变。例子:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedefvector<int> VEC_INT;
int_tmain(int argc, _TCHAR* argv[])
{
VEC_INTthevec;
cout<<"before insert data:"<<endl;
cout<<"the size of vector:"<<thevec.size()<<endl;
cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
cout<<"the max size of vector:"<<thevec.max_size()<<endl;
cout<<"after insert data:"<<endl;
thevec.push_back(42);
cout<<"the size of vector:"<<thevec.size()<<endl;
cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
cout<<"the max size of vector:"<<thevec.max_size()<<endl;
thevec.reserve(100);
cout<<"After reserve (100):"<<endl;
cout<<"the size of vector:"<<thevec.size()<<endl;
cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
cout<<"the max size of vector:"<<thevec.max_size()<<endl;
thevec.resize(1000);
cout<<"After resize (1000):"<<endl;
cout<<"the size of vector:"<<thevec.size()<<endl;
cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
cout<<"the max size of vector:"<<thevec.max_size()<<endl;
return 0;
}
运行结果:
可以看出:默认情况下,向量的大小和容量是相同的,如果用resize改变向量的大小,则同时改变了向量的容量。
更多推荐
所有评论(0)