C++ 获取向量的字节大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17254425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the size in bytes of a vector
提问by Davlog
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 的字节大小。
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?
那么我如何获得向量的大小?!也许通过将 24(向量大小)乘以项目数?
回答by AdamIerymenko
Vector stores its elements in an internally-allocated memory array. You can do this:
Vector 将其元素存储在内部分配的内存阵列中。你可以这样做:
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.
这将为您提供向量结构本身的大小加上其中所有整数的大小,但它可能不包括您的内存分配器可能施加的任何小开销。我不确定是否有一种独立于平台的方式来包含它。
回答by kfsone
You probably don't want to know the size of the vectorin 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();
回答by Thomas Russell
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.
然后只需将它们加在一起即可获得总大小。