Is there a way to get the size of vectors bytes in just one type?
Since it is vector<>
itself a class that does its own heap management, using an operator sizeof
to ask it about size doesn't make much sense. I suspect that you will find that the value you calculate above will always be 12.
You can set a vector how many elements it contains using the .size()
. Also, the method .capacity()
will tell you how many items it actually has allocated memory (even if they're not all in use yet).
Remember, it sizeof
is evaluated at compile time, so it cannot know how many elements are inserted into the container later, at runtime.
source to share
sizeof always returns the size of the first level object / type. It doesn't try to measure the amount of memory pointed to by an object elsewhere. 12 bytes, in which sizeof values reflect the size of the vector's data items. One of these elements is a pointer that points to the actual data.
source to share
There is a method called size ()
This tells you how many elements are contained inside.
But the size of the object won't reflect this as it just contains a pointer to the drive data.
By the way, you are declaring vectors of char arrays. Is this what you really want?
Also this:
std::cout << std::vector<X>(Y) << "\n";
Should (preferably) always return the same value, no matter what X or Y is.
source to share
What do you want to do exactly, do you want to know how much memory std::vector
containing 8 or 16 is taking up char
?
If this is what you want, your code above is not correct. Which is what your code above shows the size std::vector
where the elements are an array of char
s. It gives the size of the object itself std::vector
, but says nothing about the amount of memory the elements are occupying. This memory is allocated dynamically using vector
.
It is not possible to know this with an operator sizeof
because it sizeof
is a compile-time operator and the memory for the elements is dynamically allocated at run time.
source to share
Other answers have explained why you cannot use sizeof directly as you tried. However, you can use sizeof to get what you are looking for like this:
vector<int> my_vector;
// Push some stuff here
// ...
cout << my_vector.size() * sizeof(int) << endl;
my_vector.size () will return you the size in elements. Then you use sizeof (element) to get the size in bytes of each element in the array. Their product is the answer you are looking for.
source to share