简体   繁体   中英

How to do file I/O with std::vector<bool>?

I need to implement a Boolean data container that will store fairly large amount of variables. I suppose I could just use char* and implement C-style macro accessors but I would prefer to have it wrapped in an std:: structure. std::bitset<size_t> does not seem practical as it has a fixed-during-compilation size.

So that leaves me with std::vector<bool> which is optimized for space; and it has a nice bool-like accessor.

  1. Is there a way to do something like directly feed a pointer from it to fwrite() ?

  2. And how would one do file input into such a vector?

  3. And lastly, is it a good data structure when a lot of file I/O is needed?

  4. What about random file access ( fseek etc)?

EDIT: I've decided to wrap a std::vector<unsigned int> in a new class that has functionality demanded by my requirements.

  • Is there a way to do something like directly feed a pointer from it to fwrite()?

No, but you can do it with std::fstream

std::ofstream f("output.file");
std::copy(vb.begin(), vb.end(), std::ostream_iterator<bool>(f, " "));
  • And how would one do file input into such a vector?

Using std::fstream

std::ifstream f("input.file");
std::copy(std::istream_iterator<bool>(f), {}, std::back_inserter(vb));
  • And lastly, is it a good data structure when a lot of file I/O is needed?

No, vector<bool> is rarely a good data structure for any purpose. See http://howardhinnant.github.io/onvectorbool.html

  • What about random file access (fseek etc)?

What about it?

You could use a std::vector<char> , resize it to the size of the file (or other size, say you want to process fixed length blocks), then you can pass the contents of it to a function like fread() or fwrite() in the following way:

std::vector<char> fileContents;
fileContents.resize(100);
fread(&fileContents[0], 1, 100, theFileStream);

This really just allows you to have a resizable char array, in C++ style. Perhaps it is a useful starting point? The point being that you can directly access the memory behind the vector, since it is guaranteed to be laid out sequentially, just like an array.

The same concept would work for a std::vector<bool> - I'd just be careful when fread ing into this as off the top of my head I can't tell you how big ( sizeof wise) a bool is, as it depends on the platform (8bit vs 16bit vs 32bit, if you were working on a microcontroller for example).

It seems std::vector<bool> can be optimised to store each bool in a single bit, so, definitely do not attempt to use the memory behind a vector<bool> directly unless you know it is going to work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM