我正在尝试使用插入函数在trie树中插入字符串。我使用它来使用左分解方法将非确定性语法转换为确定性语法。在每个节点中我都有映射。在某处我得到分段错误。第一次使用地图所以无法弄明白。 提前致谢。
struct trie_node
{
map<char,trie_node*> char_list;
bool end_of_word;
};
trie_node* init(){
trie_node *root = (trie_node*)malloc(sizeof(trie_node));
root->end_of_word=true;
return root;
}
trie_node* new_node(){
trie_node *temp = (trie_node*)malloc(sizeof(trie_node));
temp->end_of_word = true;
return temp;
}
void insert_in_trie(trie_node *root,string s){
int n = s.length();
cout<<"bkjb";
trie_node *current = root;
for(int i=0;i<n;i++){
map<char,trie_node*>::iterator it = current->char_list.begin();
it = current->char_list.find(s[i]);
if(it!=current->char_list.end()){
current = it->second;
}
else{
cout<<"khjkk";
//make end_of_word false
current->end_of_word = false;
pair<char,trie_node*> x;
x.first = s[i];
x.second = new_node();
current->char_list.insert(x);
//update current
current = x.second;
}
}
}
void print_trie(){
cout<<"\n function print_trie"<<endl;
}
int main(){
string s[4] = {"aBcD","aBcDSe","aBcDFz","part"};
int n = sizeof(s)/sizeof(string);
//cout<<n<<endl;
trie_node *root = init();
insert_in_trie(root,"aBcDFz");
//printing trie tree
print_trie();
return 0;
}