C++ Trie数据结构的实现

C++ Trie数据结构的实现,c++,data-structures,string-matching,trie,C++,Data Structures,String Matching,Trie,我是编程新手。我正在尝试实现Trie数据结构。但每当我尝试将字符串插入trie时,就会出现分段错误 这是节点类 class Node{ public: Node *key[2]; Node *parent; bool EOW; Node1(){ this->key[0]=NULL; this->key[1]=NULL; this->pa

我是编程新手。我正在尝试实现Trie数据结构。但每当我尝试将字符串插入trie时,就会出现分段错误

这是节点类

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;
}
节点的成员密钥声明为

Node *key[2];
这是一个由两个指针组成的数组,在Trie::insertUtil中给出这一行

我将假定OP尝试插入的字符串仅由字符“0”和“1”组成

请注意,在发布的代码中,所使用的C字符串中所需的null终止符被忽略,这本身就是一个错误,可以通过使用适当的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?
        // ...
    }
    // ...
}

为什么这是C++的新成员,你使用新的?FurIt IDX=0;无效索引处的idxkey,即如果[idx]是终止零,则temp->key[a[idx]-“0']引用负索引处的元素,因为0-“0”是负的。@BartekBanachewicz,我不知道这对编程初学者意味着什么。但我对这个编程领域还不熟悉。我对基本知识知之甚少。正如我上面提到的那样,我被打动了。所以把问题放在这里。谢谢,我已经解决了。
int tmp_chr = a[idx]-'0';  // A variable ignored in the following code, BTW.
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?
        // ...
    }
    // ...
}