繁体   English   中英

向量的字节大小<bool>在 c++ 中存储 n 位</bool>

[英]The size in bytes of vector<bool> that store n bits in c++

简短:如何正确计算存储 n 位的std::vector<bool>字节的 memory 空间?

std::vector<bool> vb(n, false);
int size_bytes = compute_space_memory_in_bytes(vb);

细节:
在我的算法中,我使用vector<bool>来存储 n 位。 为了在实践中有效地测量它,我需要知道如何以字节为单位计算空间 memory。 (理论上它只是 O(n) 位)。

有2点:

  1. 如果我们有std::vector<int>则另一个答案的解决方案是:
    sizeof(std::vector<int>) + (sizeof(int) * MyVector.size())

  2. 由于向量将每个 Boolean 值存储到一个位中

一种潜在的优化涉及合并向量元素,以便每个元素占用一个位而不是 sizeof(bool) 字节。

因此,从 1 到 2,我的尝试解决方案是:

std::vector<bool> vb(100, false);
auto size_bytes = sizeof(vector<bool>) + vb.size()/8;
std::cout << "Hello, size = " << size_bytes << " bytes!\n";

那是对的吗?

编辑:更明确(感谢@PaulMcKenzie 评论):
给定要在执行时确定的 n 位。 我的问题是在 bool 向量中存储 n 位所占用的空间(精确或近似)是多少?

std::vector<bool> vb;

// some processing to get n ..

vb.resize(n);

auto size_bytes = compute size of vb in bytes ???;

std::cout << "Hello, size = " << size_bytes << " bytes!\n";

对于您重新提出的问题:

如何计算 sizeof 得到空间占用的答案

正如其他人指出的那样, vector的不同实现可能会对您的问题产生不同的答案。

一般来说,您的 boolean 值“占用”的 memory(以字节为单位)为:

int s = (n + 7) / 8;

如果您的实现使用 32 位或 64 位值将 bool 打包到向量中,则需要四舍五入到 32 或 64:

int s = (n + 31) / 32;

或者

int s = (n + 63) / 64;

有一些 memory 是vector本身使用的实例(指向第一个元素的指针、元素个数或指向最后一个元素的指针、容量等); 正如@paulsm4 所说,在他的vector实现中是 40 个字节。

您可能还想考虑已分配但尚未占用的 memory。 这也取决于实施。

总之,您绝对可以 state 只有您的向量将占用的最小大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM