//怎样给他分配10个元素的空间?(不是一次一次的插入)
//怎样给已经由元素的element重新分配10个元素的空间?(同时覆盖了原来的元素,获得新的大小)
//怎样把另外一个vector列表复制到element中?(同时覆盖了原来的元素,获得新的大小)
运行一下就行了
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(5);
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;
}
[此贴子已经被作者于2007-4-15 22:44:55编辑过]
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>vec;
for(int i=0; i<5; ++i)
{
vec.push_back(i);
}
cout<<vec.size() <<endl;
for(vector<int>::iterator itr=vec.begin();itr!=vec.end();++itr)
cout<<*itr;
cout<<endl;
vec.resize(10);
cout<<vec.size() <<endl;
for(itr=vec.begin();itr!=vec.end();++itr)
cout<<*itr;
cout<<endl;
vec.resize(1);
cout<<vec.size() <<endl;
for(itr=vec.begin();itr!=vec.end();++itr)
cout<<*itr;
cout<<endl;
return 0;
}