【发布时间】:2016-01-30 15:27:32
【问题描述】:
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <string>
using namespace std;
struct node {
bool indicator;
map<int, struct node*> vec;
};
node * create_node () {
node *newnode = new node();
newnode -> indicator = 0;
for(int i = 1; i <= 26; i++)
newnode -> vec[i] = NULL;
return newnode;
}
void insert_node (node* insertNode, int str_size, int currentIndex, string str) {
node *newNode;
newNode = create_node();
int int_convert = str[currentIndex] % 96;
insertNode -> vec[int_convert] = newNode;
currentIndex++;
if(currentIndex == str_size) {
insertNode -> vec[int_convert] -> indicator = 1;
cout<<"String added in the dictionary with certain insertions\n";
}
else
insert_node(insertNode -> vec[int_convert], str_size, currentIndex, str);
}
void travel (node* currentNode, int str_size, int currentIndex, string str) {
if(currentIndex != str_size) {
int int_convert = str[currentIndex] % 96;
if (currentNode -> vec[int_convert])
travel(currentNode -> vec[int_convert], str_size, ++currentIndex, str);
else {
char c;
cout<<"String not present\n"<<"Do u want 2 build (Y/N)\n";
cin>>c;
if (c == 'Y')
insert_node(currentNode, str_size, currentIndex, str);
}
}
else {
if(currentNode -> indicator == 1)
cout<<"String FOund in DIctionary\n";
else {
cout<<"String not in dictionary BUT can acheived without further insertions\n";
currentNode -> indicator = 1;
cout<<"String stored in dictionary\n";
}
}
}
int main() {
int num;
char C;
cout<<"enter number of insertions\n";
scanf("%d", &num);
node *rootnode;
rootnode = create_node();
for(int i =0; i < num; i++) {
string S;
cout<<"Enter string\n";
scanf("%c", &C);
getline(cin, S);
travel(rootnode, S.size(), 0, S);
}
return 0;
}
在上面的代码中,当给出超过 2 个输入时,树的根会丢失,新的树再次从 NULL 形成,消除了由先前值形成的树,因此我认为的问题是将节点传递给功能,节点地址没有得到保留。所以请弄清楚,这是一个 Trie 的程序。例如 字符串输入 1 - “顶部” 最初,树是空的,因此“top”不会出现,因此 top 将被插入树中以供将来遍历。 字符串输入 2 - “顶部” 这次它会打印“在字典中找到,因为在第一个输入中已经输入了“top”,直到这里程序响应良好 字符串输入 3 - “顶部” 当第三个输入再次为“top”时,输出应再次为“在字典中找到”,但输出为“未找到”并且再次插入“top”,因此树一次对两个输入做出正确响应,意味着第 4 个输入将对应于第 3 个输入,但它不会考虑第 1 个或第 2 个输入,类似地,在第 5 个输入时,树再次变为空并插入字符串,第 6 个输入将仅影响第 5 个输入的存在。
【问题讨论】:
-
如何确定有问题?是什么让你相信?没有什么比我更明显的错误了。
-
您的输入究竟是什么导致了问题?
-
缓冲区溢出,您正在写入一个空向量。下一次,提取一个最小的例子,因为如果你有,你可能会自己得出这个结论。投票结束作为题外话。
-
为
map精心挑选的名称。 -
@AlanStokes 让它像泥巴一样清晰,对吧?
标签: c++ pass-by-reference trie