c++primer中对vector容器的自增长问题进行了细致的说明,特别提到了两个成员函数: capacity和reserve。举了这样一段程序进行说明:
vector1
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
print(vec);
for (vector<int>::size_type ix=0;ix!=24;ix++)
{
vec.push_back(ix);
}
cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
vec.reserve(50);
while(vec.size()!=vec.capacity())
{
vec.push_back(0);
}
cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
vec.push_back(0);
cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
return 0;
}
运行结果如下所示:
我仅仅把cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;这句话替换成了函数:
void print(vector<int> vec)
{
cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
}
即把主函数变为这样:
vector2
int main()
{
vector<int> vec;
print(vec);
for (vector<int>::size_type ix=0;ix!=24;ix++)
{
vec.push_back(ix);
}
//cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
print(vec);
vec.reserve(50);
while(vec.size()!=vec.capacity())
{
vec.push_back(0);
}
//cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
print(vec);
vec.push_back(0);
// cout<<"size:"<<vec.size() <<",capacity:"<<vec.capacity()<<endl;
print(vec);
return 0;
}
结果就不再相同。结果为:
我不明白这是为什么。
还有一个问题。就是vector的sizeof问题。我在程序最后加了一句:
cout<<"size of vec:"<<sizeof(vec)<<endl;
结果在VC6.0中编译是16.在VS2008中编译是20.在G++中编译是12.
都是在同一台机器上测试的。请高手看看这是什么原因。 |