比如vector中
vector<classA> List; //classA 是一个类类型
List.reserve(4); //什么作用???不用这个函数有什么不妥?
//和resize()有什么区别??
运行一下就行了
[QUOTE]
#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;
}
[/QUOTE]
[此贴子已经被作者于2007-3-24 14:49:20编辑过]