我有一个 C++ STL 映射,它是 int 和 customType 的映射。 customType 是一个结构体,它具有字符串和字符串列表,我如何将其序列化为文件。
示例结构:
struct customType{
string;
string;
int;
list<string>;
}
最佳答案
如果你不怕 BOOST,试试 BOOST 序列化: (模板代码,这里可能有一些错误...)
#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;
}
用法:
Save< map<int, customType> >("test.map", yourMap);
关于C++ 将 std::map 序列化为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8121428/