Getting the size in bytes of a vector [duplicate]

心不动则不痛 提交于 2019-12-03 12:49:30

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.

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();

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.

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