Question

Do you know any easy or simple way to make a map object (from the STL library) persistent (i.e. write it to a file) so that you can recover its state later when the program in run later ??

Thanks for your help

Was it helpful?

Solution

I believe the Boost Serialization library is capable of serializing std::map, but the standard library itself provides no means. Serialization is a great library with a lot of features and is easy to use and to extend to your own types.

OTHER TIPS

If you want to do it manually, the same way you'd persist any other container structure, write out the individual parts to disk:

outputFile.Write(thisMap.size());
for (map<...>::const_iterator i = thisMap.begin(); i != thisMap.end(); ++iMap)
{
    outputFile.Write(i->first);
    outputFile.Write(i->second);
}

and then read them back in:

size_t mapSize = inputFile.Read();
for (size_t i = 0; i < mapSize; ++i)
{
    keyType key = inputFile.Read();
    valueType value = inputFile.Read();
    thisMap[key] = value;
}

Obviously, you'll need to make things work based on your map type and file i/o library.

Otherwise try boost serialization, or google's new serialization library.

The answer is serialization. Specifics depend on your needs and your environment. For starters, check out Boost Serialization library: http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top