sizeof() std::向量 (C++)
已经有一个关于这个主题的主题,但我仍然有疑问。要计算向量的大小,哪一个是正确的:
sizeof(VEC) + sizeof(int) * VEC.capacity()
或
VEC.capacity() * (sizeof(VEC) + sizeof(int))
There is a topic already on this topic but I have doubts still. To calculate the size of a vector, which one is correct:
sizeof(VEC) + sizeof(int) * VEC.capacity()
or
VEC.capacity() * (sizeof(VEC) + sizeof(int))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
向量的大小是什么意思?向量对象的大小只是
如果您对向量在堆上分配了多少内存感兴趣,您可以使用
因此,如果添加这些,您将获得由于以下原因“丢失”了多少内存向量。
请注意,到底分配多少内存取决于实现。只是上面的公式在大多数(如果不是全部)实现上实际上都是正确的(或近似正确的)。
What do you mean by size of the vector? The size of the vector object is just
If you are interested in how much memory the vector has allocated on the heap, you can use
So, if you add these, you'll get how much memory you've "lost" because of the vector.
Please note that exactly how much memory is allocated is implementation-dependent. It's just that the formula above will be practically correct (or approximately correct) on most if not all implementations.
如果您想知道向量中包含的数据的大小
如果类型从 int 更改为 long long 则无需更改其他任何内容。我发现这个解决方案比使用 sizeof 中的类型的解决方案更安全,因为它可以轻松地更改,而无需另一个。
If you want to know the size of the data contained within the vector
If the type is changed from int to say long long nothing else has to be changed. I find this solution safer then the one using the type in the sizeof because it one can easily be changed without the other.