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

后端 未结 6 767
星月不相逢
星月不相逢 2020-12-31 07:07

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.

sa

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 07:47

    If you are asking this, then probably you already know that you cannot serialize this by means of:

    file.write( (const char *) &mapOfCustom, sizeof( mapOfCustom ) );
    

    The problem has to do with complex objects (and in C++, even a string variable is a complex object), i.e., those objects that are not self-contained. Actually, even simple serialization has problems, which range from platform compatibilty to even compiler compatibilty (different paddings, etc.).

    One way to go is use a simple XML library such as tinyXML:

    http://www.grinninglizard.com/tinyxml/

    And write save to XML, and restore from XML procedures.

提交回复
热议问题