2013-10-29 49 views
2

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

#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 

我在很多其他的意见和代码示例上网看了一下,这两个站点和加速的文档,但我不明白如何处理这种情况是递归的这个样子。类中包含两个相同类型对象的指针。我应该如何修改树或序列化函数来使其工作?谢谢。

回答

1

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

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

您不需要宏BOOST_CLASS_TRACKING(AVLtree, track_always),Boost.Serialize会应用它,因为您将序列化(某些)AVL树作为指针。

这将工作得很好,档案被设计为处理“反指针”;递归结构对它来说是小菜一碟。

祝你好运!