【问题标题】:[c++ / pointers]: having objects A and B (B has vector member, which stores pointer to A), knowing A is it possible to retrieve pointer to B?[c++ / 指针]:拥有对象 A 和 B(B 有向量成员,其中存储指向 A 的指针),知道 A 是否可以检索指向 B 的指针?
【发布时间】:2010-11-30 16:31:14
【问题描述】:

在尝试学习 c++ 时,我尝试实现表示非常基本的 trie 的类。我想出了以下几点:

class Trie {
public:
    char data;
    vector<Trie* > children;

    Trie(char data);
    Trie* addChild(Trie* ch);    // adds child node

    (skipped others members/methods)

};

方法 addChild 检查具有相同 data 的子 ch 是否存在于向量 children 中,如果没有则如果是,则将其插入那里 - 返回指向已存在子项的指针。

现在,考虑这段代码 sn-p:

Trie t('c');
Trie* firstchild = new Trie('b');
Trie* secondchild = new Trie('a');


firstchild->addChild(secondchild);
t.addChild(firstchild);

如果我只有指向 secondchild 的指针,是否有可能以某种方式返回指向 firstchild 甚至 t 的指针?

我想知道是否可以这样做,因为我的工作代码的逻辑需要遍历 trie “up”(从较低的节点到较高的节点),到当前对象的父节点。目前我只是使用递归函数向下旅行 - 但我想知道是否存在任何其他方式?

很抱歉,如果上述内容不清楚或者我在某个地方搞砸了,我相当缺乏经验并且根据我的记忆编写,没有工作代码。

【问题讨论】:

  • addChild() 的语义很糟糕。考虑当数据已经存在时会发生什么... Trie* new_a = new Trie('a'); if(t.addChild(new_a)) 删除 new_a;如有必要,我会更好地在 addChild() 内创建新的子对象,而不是要求它从外部传入。
  • @alex tingle - 好建议,谢谢。正如我所说 - 我只是在学习。

标签: c++ data-structures pointers trie


【解决方案1】:

Trie 对象不跟踪父对象。 它基本上类似于单链表,除非你“知道”父级,否则你不能回溯。

class Trie {
public:
    char data;
    vector<Trie* > children;
    Trie* parent;

    Trie(char data):parent(NULL){}
    Trie* addChild(Trie* ch)
    { //set the parent
     ch->parent = this;
    }

    (skipped others members/methods)

};

然后遍历看起来像:

traverse(Trie* pPtr)
{
Trie* currentPtr = pPtr;
 while(currentPtr)
 {
  currentPtr = currentPtr->parent;
 }

}

【讨论】:

    【解决方案2】:

    你需要添加类似的东西

    Trie* parent;
    

    或

    Trie* previoussibling;
    Trie* nextsibling;
    

    到班级直接从firstchild 到secondchild 或反之亦然,或者从其中一个孩子上到t。

    请注意,如果您需要这种关系,则在添加和删除节点时需要更多维护以保持所有链接正确。

    【讨论】:

      【解决方案3】:

      我只有指向第二个孩子的指针, 是否有可能以某种方式返回 指向第一个孩子甚至可能 吗?

      没有。您必须通过将第一个孩子作为第二个孩子的父母来建立自己的关系。

      【讨论】:

        猜你喜欢
        • 2011-09-14
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2014-01-02
        相关资源
        最近更新 更多