views:

662

answers:

3

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

+9  A: 

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.

coppro
+2  A: 

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

sudarkoff
+5  A: 

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.

Eclipse