如何使用结构序列化映射

how to serialize map with struct

本文关键字:映射 序列化 结构 何使用      更新时间:2023-10-16

我正在尝试以结构作为键来提升序列化映射值,但是在编译代码时出现以下错误:

/usr/include/boost/serialization/access.hpp:116:11: error: ‘struct main(int, char**)::MyKey’ has no member named ‘serialize’
         t.serialize(ar, file_version);

这是我正在使用的主要代码:

#include <ros/ros.h>
#include <map>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
int main (int argc, char** argv)
{
    ros::init (argc, argv, "training");
    ros::NodeHandle nh;
    struct MyKey {
        int d0, d1, d2, a0, b0, a1, b1, a2, b2;
        bool operator < (const MyKey& o) const {
        return std::tie(d0, d1, d2, a0, b0, a1, b1, a2, b2) < std::tie(o.d0, o.d1, o.d2, o.a0, o.b0, o.a1, o.b1, o.a2, o.b2);
        }
    };
    struct MyValue {
        int p0, p1, p2;
    };
    std::map<MyKey, MyValue> pobj;
    std::ofstream s("obj_pattern"); boost::archive::text_oarchive oa(s);
    for(int i=0;i<5000000;i++) {
        pobj.insert({{i, i+1, i+2, i+3, i+4, i+5, i+6, i+7, i+8}, {i+9, i+10, i+11}});
        oa << pobj;
    }
    return 0;
}

如何删除此错误?

如果要序列化用户定义类型,则需要将序列化函数模板添加到类中。在此方法中,您可以声明序列化/还原类的哪些数据成员。

由于无法为 MyKey 的本地类移动定义定义成员函数模板,因此 MyValue 退出函数:

    struct MyKey {
        int d0, d1, d2, a0, b0, a1, b1, a2, b2;
        bool operator < (const MyKey& o) const {
        return std::tie(d0, d1, d2, a0, b0, a1, b1, a2, b2) 
                   < std::tie(o.d0, o.d1, o.d2, o.a0, o.b0, o.a1, o.b1, o.a2, o.b2);
        }
        template<class Ar>
        void serialize (Ar& ar, const unsigned int) {
            ar & d0;
            ar & d1;
            // ditto 
        }
    };
    struct MyValue {
        int p0, p1, p2;
        template<class Ar>
        void serialize(Ar& ar, const unsigned int) {
            ar & p0;
            ar & p1;
            //
        }
    };

int main (int argc, char** argv)
{
  //...
}

构建地图后,应仅调用oa << pobj;一次:

    for(int i=0;i<5000000;i++) {
        pobj.insert({{i, i+1, i+2, i+3, i+4, i+5, i+6, i+7, i+8}, {i+9, i+10, i+11}});
    }
    oa << pobj;