【问题标题】:Implementation of Trie data structureTrie数据结构的实现
【发布时间】:2020-03-09 06:38:38
【问题描述】:

我是编程新手。我正在尝试实现 Trie dataStructure。但是每当我尝试将字符串插入 trie 时都会出现分段错误。

这是 Node 类

class Node{
    public:
        Node *key[2];
        Node *parent;
        bool EOW;
        Node1(){
            this->key[0]=NULL;
            this->key[1]=NULL;
            this->parent = NULL;
            this->EOW = false;
        }
};

这是 trie 类

class Trie{
    public:
        Node *root;
        Trie(){
            root =  new Node();
        }

        void insertUtil(Node *root, char a[]);
        void insert(char a[]){
            // cout << root <<endl;
            // cout << root->key[0];
            insertUtil(root, a);
        }
};

这就是 insertUtil 函数

void Trie::insertUtil(Node *root, char a[]){
    Node *temp = root;
    for(int idx=0;idx<5;idx++){
        cout << idx <<endl;
        int tmp_chr = a[idx]-'0';
        if(!(temp->key[1])){
            temp->key[a[idx]-'0'] = new Node();
            temp->key[a[idx]-'0']->parent = temp;
        }
        temp = temp->key[a[idx]-'0'];
    }
    temp->EOW = -1;
}
int main(){
    Trie t1;
    char b[5];
    cin >> b;
    t1.insert(b);
    cout << '*';
    cin >> b;
    t1.insert(b);
    cin >> b;
    t1.insert(b);
    cin >> b;
    t1.insert(b);
}

【问题讨论】:

  • 作为一个刚接触 C++ 的人,你为什么使用 new
  • for(int idx=0;idx&lt;5;idx++) 循环看起来很可疑。如果a 是零终止的,那么循环将不可避免地到达终止零并尝试在无效索引处访问temp-&gt;key,即如果a[idx] 是终止零,那么temp-&gt;key[a[idx]-'0'] 指的是位于负索引,因为0-'0' 是负数。
  • @BartekBanachewicz,我不知道这对你的编程初学者意味着什么。但我是这个编程领域的新手。我知道一些基础知识。正如我上面提到的,我很震惊。所以把查询放在这里。

标签: c++ data-structures string-matching trie


【解决方案1】:

Node 的成员 key 声明为

Node *key[2];

所以它是一个由两个指针组成的数组,并在Trie::insertUtil 中给出这一行,

int tmp_chr = a[idx]-'0';  // A variable ignored in the following code, BTW.

我假设 OP 尝试插入的“字符串”仅由字符 '0''1' 组成。

请注意,在发布的代码中,使用的 C 字符串中所需的空终止符被简单地忽略了,这本身就是一个错误,可以通过使用适当的 std::string 来轻松修复。

另一个问题在同一个循环中:

for(int idx = 0; idx < 5; idx++)
{   //           ^^^^^^^                   It should stop before the null-terminator
    // (...)
    int tmp_chr = a[idx]-'0'; //           Are you sure that there are only '0' or '1'?
    if( !(temp->key[1]) )
    { //           ^^^                     1 is wrong, here, it should be temp->key[tmp_chr]
        temp->key[a[idx]-'0'] = new Node();
        //        ^^^^^^^^^^               Why not use tmp_chr here and in the following?
        // ...
    }
    // ...
}

【讨论】:

  • 谢谢,我知道了。
猜你喜欢
  • 2011-04-30
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多