簡體   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