C ++ Saving dynamic_bitset to file

Tracking up How to store a vector <bool> or bits in a file but broken?

Basically I write the bitrate as a binary with 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 dynamic bit method and to_block_range in a temporary vector, and then printed the blocks into a file. It works, but I double my memory usage when I use an intermediate vector (the used vector has the same size as my bit set). How can I print bits to a file without doubling the memory usage?

It would be nice if I could iterate over the bits in the blocks, but it seems that to prevent some other problems, the authors of the dynamic bitrate deliberately missed this function. Should I use a different data structure? If this helps in context, I use bit set in some flowering color code.

+4
source share
1 answer

You must do it manually. Iterate over the bits, pack them in unsigned char s and stream.put characters in a file.

Direct writing of native block_type leads to the fact that the file format depends on the specificity of a particular platform, which is usually undesirable. (And setting block_type to char can hurt performance.)

Looking at your other question, I see that this is the same as Nawaz suggested, and that you can return to using std::vector<bool> instead.

+1
source

Source: https://habr.com/ru/post/1447627/


All Articles