tags:

views:

70

answers:

2

Hello,

I have a piece of code that gives a runtime error. Can anyone help find out why?

vector<int> intData;
vector<bool> boolData;


for(int i=0;i<19000;i++)
   boolData.push_back(false);


string ofile = "tree.dat";
ofstream fout(ofile.c_str(),ios::out | ios::binary);


if (!boolData.empty()) fout.write((char *)&boolData[0], sizeof(bool)*boolData.size());
fout.close();

It gives the error when it tries to write the file (fout.write).

+4  A: 

You cannot take the address of a member of vector <bool>. That's because vector <bool> is a specialised version of std::vector, and the things stored in such a vector are not actually bools, but individual bits, which are not addressable. If you need to take the address, use a vector <char> or deque<bool> instead. If you also need the storage to be contiguous (which it seems you do, if you want to use write() ), then use vector <char>.

anon
Then why does this work?if (!intData.empty()) fout.write((char *)I read that vectors store contiguous data, so there sholdnt be a problem.
Sara
@Sara, intData is not a vector<bool>, its a vector<int>. This is an important distinction in this context
Will
@Sara Read my answer - `vector <bool>` is a *specialised* vector - exactly how it stores its contents is not specified by the C++ Standard,.
anon
Thanks, vector<char> worked.
Sara
+3  A: 

vector<bool> is specially cased in the standard (23.2.5, lib.vector.bool).

The elements in it are packed into bits not bytes, meaning you cannot take the address of an individual element.

You could change your implementation to write the underlying allocation used by your vector, but it is much more straightfoward to use a vector<char> to store your booleans instead.

My recommendation is you use vector<char>.

Will