[英]How do I serialise/deserialise a std::vector<bool> most efficiently?
我正在嘗試將std::vector<bool>
的內容寫入磁盤並寫入二進制文件。 由於許多 STL 輸出流的write()
方法接受指向數組本身的指針以及要寫入的字節數,因此對於“正常”向量,我最終會執行以下操作:
std::vector<unsigned int> dataVector = {0, 1, 2, 3, 4};
std::fstream outStream = std::fstream("vectordump.bin", std::ios::out | std::ios::binary);
outStream.write((char*) dataVector.data(), dataVector.size() * sizeof(unsigned int));
outStream.close();
但是, std::vector<bool>
是一種特殊情況,因為允許 STL 實現將std::vector<bool>
打包成單個位。 因此,上述方法在技術上不會始終有效,因為未指定數據在內存中的精確布局方式。
有沒有什么方法可以序列化/反序列化我的 bool 向量而不必打包/解包數據?
我認為您最好將該向量轉換為std::vector<std::byte>
/ std::vector<unsigned char>
。
std::vector<bool>
甚至不需要具有連續內存,因此從data()
開始寫入也是實現定義的。
不,沒有。
對不起。
避免使用此容器的好理由!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.