Getting the size in bytes of a vector

Sorry for this, maybe a simple and stupid question, but I could not find it.

I just don't know how to get the size in bytes of 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 multiplying 24 (vector size) by the number of elements?

+6
source share
3 answers

A vector stores its elements in an internal allocated memory array. You can do it:

 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 any small overhead that your memory allocator may incur. I'm not sure if this is a platform-independent way to enable this.

+5
source

You probably don’t want to know the size of the vector in bytes, because the vector is a non-trivial object that is separated from the contents located in dynamic memory.

 std::vector<int> v { 1, 2, 3 }; // v on the stack, v.data() in the heap 

What you probably want to know is the size of the data, the number of bytes needed to store the current contents of the vector. For this you can use

 template<typename T> size_t vectorsizeof(const typename std::vector<T>& vec) { return sizeof(T) * vec.size(); } 

or you can just do

 size_t bytes = sizeof(vec[0]) * vec.size(); 
+5
source

The size of the vector is divided into two main parts: the size of the container implementation itself and the size of all the elements stored in it.

To get the container implementation size, you can do what you currently have:

 sizeof(std::vector<int>); 

To get the size of all the elements stored in it, you can do:

 MyVector.size() * sizeof(int) 

Then just add them together to get the overall size.

+2
source

Source: https://habr.com/ru/post/947907/


All Articles