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

标签 c++ serialization stl

我有一个 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/

相关文章:

c++将文件连接返回给成员,因此可以由同一类的其他方法使用

c++ - boost 序列化输入流错误

java - 转换为父类并丢失信息 - 存储对象的一部分

c++ - vector 复制不起作用,但手动 push_back 可以

c++ - 当您只关心速度时如何存储二进制数据?

c++ - QDialog::exec() 阻塞应用程序

c++ - 错误 : iostream: No such file or directory

java - 多线程时如何减少文件写入次数?

java - 为什么我们需要HashMap以外的数据结构

c++ - C++ 中的通用 block 等价物