如何读写一个项目序列,其中前面的项目可能指的是后面的项目

How to read and write a sequence of items where preciding items may refer to postceding items?

本文关键字:项目 前面 读写 何读写 一个      更新时间:2023-10-16

树状结构中有许多项。我可以在树的迭代中一个一个地读取和写入它们。然而,在Item类中有一个引用指针,就像下面的

class Item
{
    Item* m_refItem;
    ...
};

如果被引用的项在树的引用项之前,我们可以在读和写时使用被引用项的索引,如下所示

void read()
{
    Index index;
    in >> index;
    m_refItem = getItem(index);
}

但是,如果被引用的项在引用项之后,则在读取引用项时,不会构造被引用的项,并且getItem(index)方法会给出错误的结果。在这种情况下如何进行阅读和写作?

您可以分两个阶段完成:

  1. 读取所有节点并存储索引
  2. 用指针替换所有索引
代码:

class Item {
    union {
        Item* m_refItem;
        int _index; }
    void read_phase_one(stream in) {
        in >> _index; }
    void read_phase_two(vector vect) {
        m_refItem = vect[index]; }