【问题标题】:C++ Depth First Search of Trie with prefix parameter带有前缀参数的Trie的C ++深度优先搜索
【发布时间】:2017-09-19 21:20:52
【问题描述】:

我正在尝试实现一个 trie,它可以打印出具有给定前缀的单词的频率。

编辑:感谢@kaidul-islam 发现我的错误并出现以下错误:

new_word->child[letter]->prefixes_++;

下面是固定代码:

Trie 类:

class Trie
{
public:
    Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
    {
        for (int i=0; i<26; i++)
        {
            child[i] = nullptr;
        }
    }
    virtual ~Trie();

    //Child nodes of characters from a-z
    Trie *child[26];
    //vector<Trie> child;

    int prefixes_;

    //accessor & mutator functions
    bool GetIsLeaf() { return is_leaf_; }
    void SetIsLeaf(bool val) { is_leaf_ = val; }
    int GetFrequency() { return frequency_; }
    void SetFrequency(int val) { frequency_ = val; }
    int GetPrefixes() { return prefixes_; }
    void SetPrefixes(int val) { prefixes_ = val; }
    bool is_leaf_;

private:
    //bool is_leaf_;
    int frequency_;
};

问题中的函数:

void AddWord(string &word, Trie *root)
{
    Trie *new_word = root;
    new_word->prefixes_++;
    for(unsigned int i = 0 ; i < word.length(); i++)
    {
        int letter = (int)word[i] - (int)'a';   //extract character of word
        if(new_word->child[letter] == nullptr)
        {
            new_word->child[letter] = new Trie;
        }

        /*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
        int x = (new_word->child[letter]->GetPrefixes())+1;
        cout << "value of x: " << x << endl;
        new_word->child[letter]->SetPrefixes(x);*/
        new_word->child[letter]->prefixes_++;

        new_word = new_word->child[letter];
    }
    new_word->SetFrequency(new_word->GetFrequency()+1);
    /*
    cout << "Word: " << word << endl;
    cout << "frequency: " << new_word->GetFrequency() << endl;
    cout << "prefixes: " << new_word->GetPrefixes() << endl;
    cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
    */
}

【问题讨论】:

  • 确保构造函数使用 nullptr 初始化所有指针。使用调试器并查看所有指针的内容。你引用而不检查,其中一个可能没有初始化......
  • 你遇到了什么错误?
  • 当我调试时,这是错误@JacoboCórdova: Program received signal SIGSEGV, Segmentation fault.

标签: c++ dictionary data-structures trie


【解决方案1】:

经过快速检查,我发现您没有在构造函数中初始化成员变量。

Trie(): prefixes_(0),
        is_leaf_(false),
        frequency_(0) {

    for(int i = 0; i < 26; i++) {
        child[i] = nullptr;
    }
}

与全局变量不同,不能保证 prefixes_ 在声明时默认为 0。并且child[i] 也不能保证是nullptr。您需要初始化所有内容。

【讨论】:

  • 哇,我不敢相信我忘记了这么小的东西。现在我只需要让搜索功能正常工作。 @kaidul-islam 你认为我应该创建一个复制构造函数,因为每个类中都有指针吗?
  • 是的,如果你需要使这个类面向位模式,你应该根据三个en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)的规则定义一个复制构造函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多