如何提升::序列化矢量的哈希图

How to Boost::serialize a hashmap of vectors?

本文关键字:哈希图 序列化 何提升      更新时间:2023-10-16

i具有将值加载到的核心数据结构:它是向量的hashmap。但是,向量包含一个结构。此外,结构使用模板类型。

我需要序列化此数据结构并定期保存到磁盘上。然后,后来 - 在一个不同的程序中 - 我需要加载串行的数据结构。

这是结构的简化版本。我最少定义它们,但是除了这个裸露的骨头版本外,还有其他数据项(成员)。

#include<vector>
#include<string>
#include<map>
#include<fstream>
#include<stdlib.h>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/map.hpp>
#include <boost/archive/text_oarchive.hpp>
using namespace std;
template<typename T>
struct DataUnit{
    size_t time;
    string transaction_string;
    T transaction;             
}
template<typename T>
struct DataStructure{
    map<string transaction_hash, vector<DataUnit<T>> > hashmap;
    int max_transactions;
    // I have a method to add stuff, but omitted for readability
} 

我从第一个结构(DataUnit)开始,然后对其进行了修改,如下所示:

    template<typename T>
struct DataUnit{
    size_t time;
    string transaction_string;
    T transaction;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version){
        ar & time;
        ar & transaction;
        ar & transaction_string;
    }
};

最终,我需要序列化数据结构。但是,当我使用以下代码运行时:

int main(){
    DataUnit<int> hi;
    hi.time = time(NULL);
    hi.transaction = 1;
    hi.transaction_string = "world";
    return 0;
}

世界因Boost的错误而炸毁。据我所知,我完全遵循了教程示例。如何增强这些对象的序列化?

一些错误(但是有很多错误,我不敢相信这不是基本的……):

在函数`boost :: Archive :: text_oarchive :: text_oarchive(std :: ostream&amp;,unsigned int)

未定义的引用`boost :: Archive :: text_oarchive_impl :: text_oarchive_impl(std :: ostream&amp; ,, unsigned int)'

最后一个错误:

未定义的引用`boost :: Archive :: Archive_exception :: 〜Archive_exception()'

它从那里持续了...但是我看不到我缺少任何东西包括...(Boost是通过Cygwin安装的)...

(以管理员的身份运行代码...我要输出的文本文件,并使用读写权限...正在成功创建OFS对象)...


当前,完全是出于想法... (尝试链接lboostrongerialization,重新安装Boost)不知道我是否缺少代码中的某些内容^^^

问题是您对构建命令的依赖的顺序。您需要在使用它们的模块之后列出依赖项。另外,您不编译.h文件。它们应包含在使用它们的.cpp文件中。尝试此命令:

g++ -std=c++11 main.cpp hashmap_transaction.cpp -o run.exe  -lboost_serialization