Sorry for this maybe simple and stupid question but I couldn't find it anywhere.
I just don't know how to get the size in bytes of a std::vector.
std::vector<int>MyVector;
/* This will print 24 on my system*/
std::cout << "Size of my vector:\t" << sizeof(MyVector) << std::endl;
for(int i = 0; i < 1000; i++)
MyVector.push_back(i);
/* This will still print 24...*/
std::cout << "Size of my vector:\t" << sizeof(MyVector) << std::endl;
So how do I get the size of a vector?! Maybe by multiplying 24 (vector size) by the number of items?
The size of a vector is split into two main parts, the size of the container implementation itself, and the size of all of the elements stored within it. Then just add them together to get the total size.
So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements.
To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.
Vector stores its elements in an internally-allocated memory array. You can do this:
sizeof(std::vector<int>) + (sizeof(int) * MyVector.size())
This will give you the size of the vector structure itself plus the size of all the ints in it, but it may not include whatever small overhead your memory allocator may impose. I'm not sure there's a platform-independent way to include that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With