Take the 2-minute tour ×

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

share|improve this question
add comment

3 Answers

up vote 10 down vote accepted

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.

share|improve this answer
add comment

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

for (map<...>::const_iterator i = thisMap.begin(); i != thisMap.end(); ++iMap)

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


