Despite the vector being called a "container", which it is from a logical perspective, from the perspective of the compiler the vector is just a (template) class which contains a pointer (or maybe several, depending on the implementation) to dynamically allocated memory and probably some other data members that are used for management of this memory. The vector class uses the dynamically allocated memory to expand and shrink, as needed.
Therefore, when using the sizeof
operator on the actual vector, you only get the size of the data members that are used for vector management and not the size of the data the vector logically "contains".
Other "container" classes with fixed length, such as std::array
or std::pair
, are probably implemented without pointers to dynamically allocated memory, so using the sizeof
operator on them will probably work as you intended. However, this is implementation-specific and cannot be relied upon.
The reason why the first element of the pair appears to take 8 bytes instead of 4 is probably an alignment issue. The first element contains a 4-byte member whereas the vector likely contains at least one 8-byte member (probably a 64-bit pointer).