Serialize sdt::map without boost

Can I serialize STL map<string, string> at once to a binary file and read back from the same?
Not in 1 step... but you can write a common routine to do it.

Simply write the number of entries ( get with size() ), then iterate through the map ( using begin() and end() ) and write the key/value pairs to the file.
thank you!
I'm sorry but I have another question...

I did my "store routine" :

void store (fstream &stream) {
map<string,string>::iterator it;

stream.write ((char*)&name, sizeof (string));
stream.write ((char*)&basecalls, sizeof (string));
stream.write ((char*)&quality, sizeof (string));
for (it=directionPosition.begin(); it!=directionPosition.end(); it++) {
stream.write ((char*)&(it->first), sizeof(string));
stream.write ((char*)&(it->second), sizeof(string));
}
}

and it seems to work, but I really don't know how I can retrieve my data in my binary file...because I can't do a "for" loop, cause I don't know how many entries I have...Could you help me?

About the first three elements it's not a problem I can do this :

void retrieve (fstream &stream) {
stream.read ((char*)&name, sizeof(string));
stream.read ((char*)&basecalls, sizeof(string));
stream.read ((char*)&quality, sizeof(string));
}


That's not going to work. string is a class containing pointers. You can't write the pointers to the file (well, you can, but it is useless).

Write the number of elements in the map to the file first.
thanks.

But if it isn't a good idea to write string (pointers) into the file, I can't see what I have to do...

maybe my store method could be just like this ?

1
2
3
4
void store (fstream &stream) {
   stream.write ((char*)&size, sizeof (int)); //map size
   stream.write ((char*)&MyObject, sizeof (Object));
}

?

and for retrieve my object, I take the size and then loop on size, taking out values ?
To write a string object, you will need to

1
2
3
4
5
string str;   // String to write
size_t strSz( str.length() );

stream.write( &strSz, sizeof( strSz ) );
stream.write( str.c_str(), strSz );


ie, write the length of the C-string first, then write the data.
Topic archived. No new replies allowed.