Is an empty vector the size of its struct?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

Say I have a struct like this:

struct vertexNodeInfo {     unsigned char level;     int node;     double leaf; }; 

If I then had this:

vector<vertexNodeInfo> node; 

How big (memory-wise, not .size) would the empty vector be, before any push_back? Would it be exactly the same size (again, in terms of memory) as vector<int> node;?

回答1:

There's no requirement. Even more, it's a poorly formulated question.

The .size of the vector would be 0, because it has no elements.

The sizeof isn't affected the number of elements, and is typically large enough to contain one or two of pointers to the type (which can vary in size themselves, so there's no guarantee the sizeof(vector<vertexNodeInfo>) and sizeof(vector<int>) are equal), the size and capacity.



回答2:

As Luchian says, it is likely but not required that sizeof(vector<int>) == sizeof(vector<vertexNodeInfo>).

Furthermore, I don't believe the standard makes any requirement as to the capacity of a default-initialized vector:

Initial capacity of vector in C++

So it's permitted to have a capacity of 10, meaning that it has allocated enough memory for 10 elements up front. Then the size of this allocation would of course depend on the size of the elements. You don't exactly define what you mean by "how big, memory-wise", but if you mean to include dynamic allocations then this would be one.

I don't think that would be a very good implementation of vector, but it conforms to the standard.



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