【问题标题】:De/serialize object with map?用地图反序列化对象?
【发布时间】:2016-11-20 21:55:47
【问题描述】:

给定结构示例:

struct SomeName
{
    SomeName()
    {
    }

    ~SomeName()
    {
    }

    unsigned int Id;
    std::string Name;
    std::map<unsigned int, unsigned int> Todo;
}

如何将 std::vector 序列化为二进制文件?

我试过了:

bool Save(std::string filename, std::vector<SomeName> &items)
{
    std::ofstream fileWrite;
    fileWrite.open(filename.c_str(), std::ios::out | std::ios::binary);
    if (!fileWrite)
    {
        std::cout << "Failed to open file for writting...\n";
        return false;
    }
    fileWrite.write(reinterpret_cast<const char*>(&items[0]), items.size()*sizeof(SomeName));
    fileWrite.close();
    return true;
}

它可以生成 dat 文件,但是在读回它时总是失败,因为它里面有 std::map。

我试图理解崩溃消息,这是一个访问冲突,它让我相信它不明白如何初始化映射以在读回文件时填充它?或者类似的东西,我不明白。

访问冲突读取位置0xfeeeff03。

指回// &lt;&lt;&lt; THIS LINE

_Nodeptr _Copy(_Nodeptr _Rootnode, _Nodeptr _Wherenode)
    {   // copy entire subtree, recursively
    _Nodeptr _Newroot = _Myhead;    // point at nil node

    if (!_Isnil(_Rootnode)) // <<< THIS LINE
        {   // copy a node, then any subtrees
        _Nodeptr _Pnode = _Buynode(_Myhead, _Wherenode, _Myhead,

SerializationCpp.exe!std::_Tree,std::allocator >,0> >::_Copy(std::_Tree_nod,std::allocator >,0> >::_Node * _Rootnode, std::_Tree_nod, std::allocator >,0> >::_Node * _Wherenode) 第 1078 行 + 0xc 字节 C++

我是这样读回来的:

bool Load(std::string filename, std::vector<SomeName> &items)
{
    items.clear();
    std::ifstream file;
    file.open(filename.c_str(), std::ios::in | std::ios::binary);
    if (!file)
    {
        std::cout << "Failed to open file for reading...\n";
        return false;
    }

    SomeName temp;
    while (file.read(reinterpret_cast<char*>(&temp), sizeof temp))
    {
        items.push_back(temp);
    }
    file.close();
    return true;
}

在简历中,如何从二进制文件序列化/反序列化该结构?

【问题讨论】:

    标签: dictionary serialization vector stl c++98


    【解决方案1】:

    这个结构不能仅仅通过将它解释为 char 数组来序列化,因为它的一部分是指动态内存。使用一些序列化库(例如 boost 序列化或 google protobuf)。

    或者,您可以手动实现序列化例程,但这项工作非常繁琐且容易出错:

    1. ID 写入文件
    2. Name.length() 写入文件
    3. Name.data() 写入文件
    4. Todo.length() 写入文件
    5. Todo 的每个成员写下它的键和值

    【讨论】:

    • 信息量很大,我认为这是可能的,因为它可以在没有地图的情况下按预期工作。
    猜你喜欢
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多