Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistence of std::map in C++

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

like image 505
lurks Avatar asked Sep 26 '08 03:09

lurks


3 Answers

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.

like image 126
coppro Avatar answered Oct 11 '22 19:10

coppro


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.

like image 26
Eclipse Avatar answered Oct 11 '22 20:10

Eclipse


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

like image 25
sudarkoff Avatar answered Oct 11 '22 19:10

sudarkoff