C++ 如何发现 std::vector 的大小/长度(以字节为单位)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14238430/
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
How can I discover the size/length(in bytes) of a std::vector?
提问by Vahid Haratian
I have a vector and I want to write and read it to a file but it is not possible to determine the logical size of a vector using the sizeof
operator.
我有一个向量,我想将它写入和读取到文件中,但无法使用sizeof
运算符确定向量的逻辑大小。
So what shall I do?
那我该怎么办?
回答by Ivaylo Strandjev
A c++ std::vector has a method size()
which returns its size.
C++ std::vector 有一个size()
返回其大小的方法。
EDIT: as I get it now you need to compute the memory a given vector uses. You can't use sizeof for that as a vector uses dynamic memory and stores only a pointer of a dynamic array containing its elements. So my best suggestion would be to multiply the memory each element requires by the number of elements. Note this again will not work if the objects stores a pointer to some dynamically allocated objects - you will have again to compute their sizes separately.
编辑:据我所知,您需要计算给定向量使用的内存。您不能为此使用 sizeof,因为向量使用动态内存并仅存储包含其元素的动态数组的指针。所以我最好的建议是将每个元素所需的内存乘以元素数量。请注意,如果对象存储指向某些动态分配对象的指针,这将再次不起作用 - 您将再次分别计算它们的大小。
There is no easy way to compute the memory a vector size in bytes in c++ that I know of.
据我所知,没有简单的方法可以在 C++ 中以字节为单位计算内存向量大小。