【问题标题】:Boost Serialization of a Tree?提升树的序列化?
【发布时间】:2013-10-29 21:34:06
【问题描述】:

我有一个需要序列化的树类。代码:

#include <string>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/tracking.hpp>
using namespace std;

class AVLtree {
public:
    string name;
    int fid;
    int p1;
    int n1;
    double ig;

    AVLtree *left;  // left subtree
    AVLtree *right; // right subtree
    int height;     // height of the tree
    long TotalNodes;
};
BOOST_CLASS_TRACKING(AVLtree, track_always)
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive &ar, AVLtree &tree, const unsigned int version) {
    ar & tree.name;
    ar & tree.fid;
    ar & tree.p1;
    ar & tree.n1;
    ar & tree.ig;
    ar & tree.height;
    ar & tree.TotalNodes;
    ar & *tree.left; // Haven't yet tried it with *tree.left, but just tree.left saves the memory address, not the object
    ar & *tree.right;
} // end serialize()
} // end namespace serialization
} // end namespace boost

我在网上查看了很多其他 cmets 和代码示例,包括这个站点和 Boost 文档,但我不知道如何处理这样的递归情况。其中类包含相同类型的对象的两个指针。我应该如何修改树或序列化函数以使其工作?谢谢。

【问题讨论】:

    标签: c++ boost-serialization gcc4


    【解决方案1】:

    恕我直言,您应该tree.lefttree.right 序列化为指针,而不是对象。它们有时可以并且应该等于 NULL(否则您的树将是无限的)。

    您的代码还需要一个适当的默认构造函数,将这些成员设置为 NULL。从您的代码中也不清楚谁拥有和销毁这些树。我会考虑禁止复制构造函数(例如,从 boost::noncopyable 派生你的类)。

    您不需要宏 BOOST_CLASS_TRACKING(AVLtree, track_always),Boost.Serialize 无论如何都会应用它,因为您会将(一些)AVLtree 序列化为指针。

    这样就可以了,存档旨在处理“反向指针”;递归结构对它来说是小菜一碟。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 2011-09-07
      • 2013-08-25
      相关资源
      最近更新 更多