sizeof(Vector<>)大小問題


先來看一個例子:

struct record{
     string name;
     int age;
     vector<int> grades;
};

則sizeof(record)大小為多少?

答案是:20(G++編譯器下)

了解string,int的朋友很熟悉,string和int在G++下都是4字節,這樣看來 grades的大小應為12字節。

給grades中放入三個整型值,100,110,120,sizeof(grades),竟然還是12!

由此說來,sizeof(vector<type>)的大小,跟容器里面存放多少數據無關,它是在編譯期確定的一個值,僅跟具體的編譯器有關。

用一段程序測試一下:

cout<<"sizeof(vector<char>) = "<<sizeof(vector<char>)<<endl;
cout<<"sizeof(vector<int>) = "<<sizeof(vector<int>)<<endl;
cout<<"sizeof(vector<short>) = "<<sizeof(vector<short>)<<endl;
cout<<"sizeof(vector<double>) = "<<sizeof(vector<double>)<<endl;
cout<<"sizeof(vector<long>) = "<<sizeof(vector<long>)<<endl;
cout<<"sizeof(vector<float>) = "<<sizeof(vector<float>)<<endl;
cout<<"sizeof(vector<bool>) = "<<sizeof(vector<bool>)<<endl;
cout<<"sizeof(vector<string>) = "<<sizeof(vector<string>)<<endl;

結果如下:

可以看出除了bool類型外,其他類型的容器大小均為12字節,經檢測VC6.0下這個值是16,在VS2003以后該值是20.

所以,要想查看一個容器v的大小:

可以使用sizeof(v) + sizeof(T) * v.capacity();//T是v中元素類型


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM