短:
如何正确计算 std::vector<bool>
的内存空间(以字节为单位)那存储n位?
std::vector<bool> vb(n, false);
int size_bytes = compute_space_memory_in_bytes(vb);
详情:在我的算法中,我使用
vector<bool>
存储 n 位。为了在实践中有效地衡量它,我需要知道如何以字节为单位计算空间内存。 (理论上它只是 O(n) 位)。有2点:
std::vector<int>
, the solution from another answer是:sizeof(std::vector<int>) + (sizeof(int) * MyVector.size())
One potential optimization involves coalescing vector elements such that each element occupies a single bit instead of sizeof(bool) bytes.
因此,从 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 的 vector 中存储 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";
最佳答案
对于您重申的问题:
How to compute the sizeof to get the answer of space occupied
正如其他人所指出的,
vector
的不同实现可能会对您的问题产生不同的答案。一般来说,您的 boolean 值“占用”的内存(以字节为单位)是:
int s = (n + 7) / 8;
如果您的实现使用 32 位或 64 位值将 bool 打包到 vector 中,则您需要四舍五入为 32 或 64:int s = (n + 31) / 32;
或者int s = (n + 63) / 64;
有一些内存是 vector
的实例本身使用(指向第一个元素的指针、元素数量或指向最后一个元素的指针、容量等);正如@paulsm4 所说,在他的 vector
实现中是 40 个字节。 .您可能还想考虑已分配但尚未占用的内存。这也取决于实现。
总之,您绝对可以仅说明您的 vector 将占用的最小大小。
关于c++ - 在 C++ 中存储 n 位的 vector<bool> 的大小(以字节为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67338591/