C ++将std :: map序列化到文件 [英] C++ Serializing a std::map to a file

查看:1998
本文介绍了C ++将std :: map序列化到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

sample struct:

struct customType{
string;
string;
int;
list<string>;
}


推荐答案

如果你不害怕BOOST,try BOOST Serialize:
(模板代码,这里可以有一些错误...)

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;
} 

用法:

Save< map<int, customType> >("test.map", yourMap); 

这篇关于C ++将std :: map序列化到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆