Writing contents of an std::vector to a binary file! ;o)

This is a discussion on Writing contents of an std::vector to a binary file! ;o) within the C++ Programming forums, part of the General Programming Boards category; Hi,
I have already written the contents of a regular good old array to a bin file many times. The ...

Writing contents of an std::vector to a binary file! ;o)

Hi,

I have already written the contents of a regular good old array to a bin file many times. The program I've made needs some resizing to take place in it though - std::vector needed. But I want to write the contents of that std::vector out to a binary file. Up to now it's used this command for a regular array:

Vectors aren't contiguous blocks of memory, so you can't simply write the block of memory to a file. Instead, you'll have to manually write each element (assuming each element is itself a contiguous block of memory, i.e. no pointers). You should be able to do something clever with std::copy and an OutputIterator, if that's closer to what you were looking for.

Perhaps this is a defect in the C++ standard, as std::string has the same problem, but the intent is that vector is contiguous. If your implementation does not store a vector in contiguous memory, it should not be considered as conforming to the Standard.

As the fix to store std::strings in contiguous memory is vector<char>, it had better be guaranteed to be contiguous.

Vectors aren't contiguous blocks of memory, so you can't simply write the block of memory to a file.

Vectors contents are meant to be guaranteed by the standard to be contiguous in memory. The problem here is that you cant cast the vector itself that way. You instead need to get the address of the first item.

The following is a legitimate way of doing it. Also note the other changes I made: