C ++将dynamic_bitset存储到文件中 [英] C++ Storing a dynamic_bitset into a file
问题描述
排序后续如何存储一个向量< bool>
基本上,我写一个bitset作为二进制文件,具有以下代码:
boost :: dynamic_bitset< boost :: dynamic_bitset<> :: block_type>过滤;
vector< boost :: dynamic_bitset<> :: block_type> filterBlocks(filter.num_blocks());
//填充向量块
boost :: to_block_range(filter,filterBlocks.begin());
ofstream myFile(filterFilePath.c_str(),ios :: out | ios :: binary);
//写出每个块
for(vector< boost :: dynamic_bitset<> :: block_type> :: iterator it =
filterBlocks.begin = filterBlocks.end(); ++ it)
{
//检索块并将其转换为char *
myFile.write(reinterpret_cast< char *> ),
sizeof(boost :: dynamic_bitset<> :: block_type));
}
myFile.close();
我使用动态bitset和to_block_range的方法到一个临时向量,然后打印出文件。它工作,但我加倍我的记忆使用,当我使用中间向量(使用的矢量是我的bitset相同的大小)。如何将bitset打印到一个文件,而不加倍我的内存使用?
这将是很好,如果我可以迭代通过bitset在块,但似乎,以防止一些其他问题,动态bitset的作者故意忽略这种功能。我应该使用不同的数据结构吗?如果它有助于上下文我在一个布隆过滤器代码中使用bitset。
迭代这些位,将它们分别包含到 unsigned char
s和 stream.put
中。 p>
直接编写原生 block_type
会导致文件格式取决于平台特定的字节顺序,这通常是不希望的。 (并将 block_type
设置为 char
会损害性能。)
看看你的其他问题,我看到这和Nawaz建议的一样,你可能想回到使用 std :: vector< bool>
Sort of a follow up to How does one store a vector<bool> or a bitset into a file, but bit-wise?
Basically I am writing a bitset as a binary file with the follow code:
boost::dynamic_bitset<boost::dynamic_bitset<>::block_type> filter;
vector<boost::dynamic_bitset<>::block_type> filterBlocks(filter.num_blocks());
//populate vector blocks
boost::to_block_range(filter, filterBlocks.begin());
ofstream myFile(filterFilePath.c_str(), ios::out | ios::binary);
//write out each block
for (vector<boost::dynamic_bitset<>::block_type>::iterator it =
filterBlocks.begin(); it != filterBlocks.end(); ++it)
{
//retrieves block and converts it to a char*
myFile.write(reinterpret_cast<char*>(&*it),
sizeof(boost::dynamic_bitset<>::block_type));
}
myFile.close();
I used the method of dynamic bitset and to_block_range into a temporary vector, then printing out the blocks into the file. It works but I am doubling my memory usage when I use an intermediate vector (vector used is the same size of my bitset). How can I print the bitset to a file without doubling my memory usage?
It would be nice if I could iterate through the bitset in blocks but it seems, to prevent some other problems, the authors of the dynamic bitset intentionally omitted this sort of functionality. Should I use a different datastructure? If it help for context I am using the bitset in a some bloom filter code.
You should do it manually. Iterate over the bits, pack them into unsigned char
s, and stream.put
the chars into the file.
Directly writing the native block_type
causes the file format to depend on platform-specific endianness, which is generally undesirable. (And setting block_type
to char
would harm performance.)
Looking at your other question, I see that this is the same as what Nawaz suggested, and that you might want to go back to using std::vector<bool>
instead.
这篇关于C ++将dynamic_bitset存储到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!