如何发现std :: vector的大小/长度(以字节为单位)? [英] How can I discover the size/length(in bytes) of a std::vector?

查看:238
本文介绍了如何发现std :: vector的大小/长度(以字节为单位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量,我想将其写入和读取到文件中,但是无法使用 sizeof 运算符确定向量的逻辑大小.

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.

那我该怎么办?

推荐答案

一个c ++ std :: vector具有一个 size()方法,该方法返回其大小.

A c++ std::vector has a method size() which returns its size.

到现在为止,您需要计算给定向量使用的内存.您不能为此使用sizeof,因为向量使用动态内存并且仅存储包含其元素的动态数组的指针.因此,我最好的建议是将每个元素所需的内存乘以元素数量.请注意,如果对象存储指向一些动态分配的对象的指针,这将再次不起作用-您将不得不再次分别计算它们的大小.

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.

在我所知的c ++中,没有简单的方法来计算内存的向量大小(以字节为单位).

There is no easy way to compute the memory a vector size in bytes in c++ that I know of.

这篇关于如何发现std :: vector的大小/长度(以字节为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆