C++将std :: map序列化为文件

jar*_*nks 14 c++ serialization stl

我有一个C++ STL映射,它是int和customType的映射.customType是一个结构,它有字符串和字符串列表,如何将其序列化为文件.

示例结构:

struct customType{
string;
string;
int;
list<string>;
}
Run Code Online (Sandbox Code Playgroud)

Max*_*nko 10

如果您不怕BOOST,请尝试BOOST Serialize :(模板代码,这里可能有些错误...)

#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;
} 
Run Code Online (Sandbox Code Playgroud)

用法:

Save< map<int, customType> >("test.map", yourMap); 
Run Code Online (Sandbox Code Playgroud)


Som*_*ude 7

一个简单的解决方案是在一行上输出每个成员,包括列表中的所有字符串.每条记录都以地图的键开头,并以不在列表中的特殊字符或字符序列结束.通过这种方式,您可以一次读取一行,并知道第一行是地图键,第二行是结构中的第一个字符串,依此类推,当您到达特殊记录结束序列时,您知道列表已完成这是地图中下一个项目的时间.此方案使文件生成可读,如果您需要在程序外编辑它们,则可编辑.