How can I discover the size/length(in bytes) of a std::vector?

匿名 (未验证) 提交于 2019-12-03 02:50:02

问题:

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.

So what shall I do?

回答1:

A c++ std::vector has a method size() which returns its 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.

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



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