Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the size in bytes of a vector [duplicate]

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?

like image 252
Davlog Avatar asked Jun 22 '13 19:06

Davlog


People also ask

How do you find the size of a vector in a byte?

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.

How many bytes is a std::vector?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements.

How do you find the size of a vector in C++?

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.


1 Answers

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.

like image 52
AdamIerymenko Avatar answered Sep 27 '22 22:09

AdamIerymenko