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.
都是在同一台機器上測試的。請高手看看這是什麼原因。