I tried to print the number of byte and the memory address of elements that are in a vector. The result, I see a memory address and a number of byte. Are the elements of a vector stored separately? And if so, why does my code give me that the vector is only 24 bytes?
#include <iostream>
#include <vector>
int main(){
std::vector<const char *> colour = {"Microsoft", "Apple", "DELL", "Accer", "Lenovo", "hp"};
std::cout << "VectorSize : " << sizeof(colour) << "\n" << std::endl;
for(int i = 0; i < colour.size(); i++){
std::cout << colour[i] << " is " << sizeof(colour[i]) << " byte at " << &colour[i] << "." << std::endl;
}
}
VectorSize : 24
Microsoft is 8 byte at 0x27b5a7c6220.
Apple is 8 byte at 0x27b5a7c6228.
DELL is 8 byte at 0x27b5a7c6230.
Accer is 8 byte at 0x27b5a7c6238.
Lenovo is 8 byte at 0x27b5a7c6240.
The data in a vector is allocated dynamically and stored in another memory location, it is not part of the vector, and the vector only has a pointer to this memory. The allocated memory is contiguous, so all allocated bytes are next to each other in memory.
In your case it the size of the class std::vector is 24 bytes, the size of the extra allocated memory somewhere else in memory is 40 bytes. So in total 64 bytes will be allocated in your computers memory.