The Int size is 4, and the vector <int> VEC is defined. There is an element in VEC, sizeof (VEC) = 20. If there are 1000 elements, what is sizeof (VEC?
# Include <iostream> # include <vector> using namespace STD; int main () {vector <int> VEC; For (INT I = 0; I <100; I ++) {Vec. push_back (I); cout <sizeof (VEC) <Endl; cout <Vec. size () <Endl ;}}
Output result:
201 ...... 20100 press any key to continue...
We can see that:Sizeof (VEC) depends only on the Data Type stored in the vector and has nothing to do with the number of elements. This value should be related to the compiler.
# Include <iostream> # include <vector> using namespace STD; int main () {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 ;}
Output:
Sizeof (vector <char>) = 20 sizeof (vector <int>) = 20 sizeof (vector <short>) = 20 sizeof (vector <double>) = 20 sizeof (vector <long>) = 20 sizeof (vector <float>) = 20 sizeof (vector <bool>) = 28 sizeof (vector <string>) = 20 press any key to continue...
Why is the size 20, and some are 28? Is it related to the container type?
Explanation:
The vector should allocate memory from the heap. All sizes are irrelevant to the number of elements.
Sizeof (vector) depends on the specific implementation of the Vector class. STL is completely open, and anyone can implement the Vector class.
By viewing the STL source code, we can see that the vector has four member variables.
_ A Allocator;
Iterator _ first, _ last, _ end;
Each pointer is 4 bytes, so 16 bytes. Does the 20-byte pointer have been added?