Getting the size in bytes of a vector [duplicate]

主宰稳场 提交于 2019-12-04 19:21:49

问题


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?


回答1:


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.




回答2:


You probably don't want to know the size of the vector in bytes, because the vector is a non-trivial object that is separate from the content, which is housed 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 required to store the current contents of the vector. To do this, you could use

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

or you could just do

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



回答3:


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.

To get the size of the container implementation you can do what you currently are:

sizeof(std::vector<int>);

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

MyVector.size() * sizeof(int)

Then just add them together to get the total size.



来源:https://stackoverflow.com/questions/17254425/getting-the-size-in-bytes-of-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!