【问题标题】:Leetcode 208 about TRIE. What's wrong with my deconstructor? It never works [closed]Leetcode 208 关于 TRIE。我的解构器有什么问题?它永远不会起作用[关闭]
【发布时间】:2018-01-04 16:52:29
【问题描述】:
#include <string>
using std::string;

class Trie
{
private:
    Trie* p[26];
    bool end;
    void clear(Trie* pt)
    {
        for (int i = 0; i < 26; ++i)
        {
            if (pt->p[i])
            {    
                clear(pt->p[i]);
                delete pt->p[i];
            }
        }
    }
public:
    Trie():p(), end(false)
    {}

    void insert(string word)
    {
        Trie* pt = this;
        for (int i = 0; i < word.size(); ++i)
        {
            int idx = word[i] - 'a';
            if (!pt->p[idx])
            {
                pt->p[idx] = new Trie();
            }
            pt = pt->p[idx];
        }
        pt->end = true;
    }

    ~Trie()
    {
        clear(this);
    }
};

我在VS中调试,发现每次运行这行delete pt->p[i],都会再次调用解构函数,然后递归调用clear()函数。

此外,pt->p[i] 仍然指向同一个内存块,只是它不可访问。

在 leetcode 中这个问题的讨论部分,大多数解决方案首先构建一个类 TrieNode,所以如果删除 TrieNode 不会引起问题,但我只是想知道我是否可以只使用一个类定义来让我的代码工作。

提前感谢!

【问题讨论】:

    标签: c++ algorithm class trie


    【解决方案1】:

    对于给定的i,您将清除p[i] 两次。

    访问:clear(pt-&gt;p[i]);

    第二次在delete pt-&gt;p[i]; 中调用clear(this),其中this 与父级的pt-&gt;p[i] 相同。

    您应该跳过 clear(pt-&gt;pt[i]) 调用,因为它由析构函数处理。

    至于指针仍然存在,这正是应该发生的事情。在delete pt-&gt;p[i] 之后,你可以为空pt-&gt;p[i]

    PS:s/deconstructor/destructor/

    【讨论】:

    • 非常感谢@Marc。我已经考虑了 2 天。
    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2013-06-03
    • 2016-07-06
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多