Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Serializing a std::map to a file

I have a C++ STL map, which is a map of int and customType. The customType is a struct, which has string and a list of string, How can i serialize this to a file.

sample struct:

struct customType{
string;
string;
int;
list<string>;
}
like image 999
jarjarbinks Avatar asked Nov 14 '11 12:11

jarjarbinks


3 Answers

If you are not afraid of BOOST, try BOOST Serialize: (template code, here can be some errors...)

#include <boost/archive/binary_oarchive.hpp> 
#include <boost/archive/binary_iarchive.hpp> 
#include <boost/serialization/map.hpp> 
#include <boost/serialization/string.hpp> 
#include <boost/serialization/list.hpp> 

struct customType{
 string string1;
 string string2;
 int i;
 list<string> list;

// boost serialize 
private: 
    friend class boost::serialization::access; 
    template <typename Archive> void serialize(Archive &ar, const unsigned int version) { 
        ar & string1; 
        ar & string2; 
        ar & i;
        ar & list;
    } 
};

template <typename ClassTo> 
int Save(const string fname, const ClassTo &c) 
{ 
    ofstream f(fname.c_str(), ios::binary);
    if (f.fail()) return -1;
    boost::archive::binary_oarchive oa(f); 
    oa << c; 
    return 0;
} 

Usage:

Save< map<int, customType> >("test.map", yourMap); 
like image 94
Max Tkachenko Avatar answered Oct 16 '22 08:10

Max Tkachenko


A simple solution is to output each member on a line on its own, including all the strings in the list. Each record start with the key to the map, and ends with a special character or character sequence that can not be in the list. This way you can read one line at a time, and know the first line is the map key, the second line the first string in the structure and so on, and when you reach your special record-ending sequence you know the list is done and it's time for the next item in the map. This scheme makes the files generated readable, and editable if you need to edit them outside the program.

like image 7
Some programmer dude Avatar answered Oct 16 '22 09:10

Some programmer dude


C++ doesn't have reflection capabilities like Java and others, so there's no 'automatic' way of doing that. You'll have to do all the work yourself: open the file, output each element in a loop, and close the file. Also there's no standard format for the file, you'd need to define one that meets your needs. Of course, there are libraries out there to help in this, but they aren't part of the language. Take a look at this question:

Is it possible to automatically serialize a C++ object?

Also take a look at: http://s11n.net/

like image 2
Fabio Ceconello Avatar answered Oct 16 '22 08:10

Fabio Ceconello