关于vector的capacity和sizeof的疑问
副标题#e#
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;
}
#p#副标题#e#
即把主函数变为这样:
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.
都是在同一台呆板上测试的。请好手看看这是什么原因。