我已经干运行了这个带有配对类的尝试实现,但它没有给出预期的输出。我做错了什么?

  • 本文关键字:错了 输出 运行 实现 c++ class trie
  • 更新时间 :
  • 英文 :

#include<iostream>
using namespace std;
class trieNode{
public:
int data;
bool isTerminal;
trieNode ** children;
trieNode(int data){
this->data = data;
children = new trieNode*[26];
for(int i=0;i<26;i++){
children[i] = NULL;
}
isTerminal = false;
}
};
class Pair{
public:
bool exist;
trieNode* address;
Pair(){
exist = false;
address = NULL;
}
};
class Trie{
public:
trieNode *root;
Trie(){
root = new trieNode('');
}
// for programmer
private:
void insert(trieNode* root,string word){
//base case
if(word.size() == 0){
root->isTerminal = true;
return ;
}
// small calculation
int index = word[0] - 'a';
trieNode *child;
if(root->children[index] != NULL){
child = root->children[index];
}
else{
child = new trieNode(word[0]);
root->children[index] = child;
}
// recursion
insert(child,word.substr(1));
}
// for user
public:
void insertWord(string word){
insert(root,word);
}
// for programmer
private:
void deleteWord(trieNode* root, string word){
if(word.size() == 0){
root->isTerminal = false;
return;
}
int index = word[0] - 'a';
trieNode *child;
if(root->children[index] != NULL){
child = root->children[index];
}
else{
return;
}
deleteWord(child,word.substr(1));
if(child->isTerminal == false){
for(int i=0;i<26;i++){
if(child->children[i] != NULL)
return;
}
delete child;
root->children[index] = NULL;
}       
}
// delete word 
//for user
public:
void deleteWord(string word){
deleteWord(root,word);
}
// search a sting in trie
//function for programmer
// i used a pair class as return type brcause i want to return if word exists then return it's 
address too
// i.e return a bool = true and adress where the word ends
private:
Pair find(trieNode *root, string word){
Pair p;
if(word.size() == 0){
Pair p;
p.address = root;
if(root->isTerminal == true)
p.exist = true;
else
p.exist = false;
return p;
}
trieNode *child;
int index = word[0]-'a';
if(root->children[index] == NULL){
Pair p;
p.address = root;
p.exist =  false;
return p;
}
else{
child = root->children[index];
p = find(child, word.substr(1));
}
}
// search a string in the trie
// function for user
public:
Pair findstr(string word){
Pair p;
p = find(root,word);
return p;
}
};
int main(){
Trie t;
t.insertWord("sucess");
t.insertWord("s");
t.insertWord("a");
Pair p;
p = t.findstr("sucess");
cout<< p.address->data <<" "<< p.exist<<endl;
p = t.findstr("s");
cout<< p.address->data <<" "<< p.exist<<endl; 
p = t.findstr("a");
cout<< p.address->data <<" "<< p.exist;

我使用pair类来实现一个名为findstr的函数,该函数在trie中找到一个单词,并返回两个东西,一个bool和单词的最后一个trieNode的地址,为此我使用了一个pair类,在该代码中,它应该以十六进制返回地址,并且三个都为true,但我只能看到垃圾值

}

这里有一个问题

else{
child = root->children[index];
p = find(child, word.substr(1));
}

应该是

else{
child = root->children[index];
p = find(child, word.substr(1));
return p;
}

编译器本应向您发出有关缺少返回语句的警告。你忽略了吗?

代码可能还有许多其他问题。如前所述,要做的是使用调试器。比在SO.上询问更快的方法来修复你的错误

相关内容

最新更新