我正在实现一个trie,一旦到达单词的末尾,它也会打印定义。我使用字符串作为定义。但是当我将定义赋值给字符串时,代码崩溃了。
#include <bits/stdc++.h>
#define ALPHABET_SIZE 26
#define CHAR_TO_INDEX(c) ((int)c - (int)'0')
using namespace std;
typedef struct trienode{
string definition; //For Definition of the word
bool isLeaf;
struct trienode *children[ALPHABET_SIZE];
}node;
node* getnode()
{
int i;
node *t=new node();
t->isLeaf=false;
for(i=0;i<26;i++)
{
t->children[i]=NULL;
}
return t;
}
void insert(node *root,string s)
{
node *crawler=root;
int level,index,length=s.length();
for(level=0;level<length;level++)
{
index= CHAR_TO_INDEX(s[level]);
if(crawler->children[index]==NULL)
{
crawler->children[index]=getnode();
}
crawler=crawler->children[index];
}
crawler->definition= "Definition of" + s; //Here is the code crashing,when I am assigning the definition
crawler->isLeaf=true;
}
你的代码有很多问题。
我看到的更大的,(我认为)导致崩溃的问题,在下一行
#define CHAR_TO_INDEX(c) ((int)c - (int)'0')
当c
是一个表示数字的字符(从0
到9
)时,CHAR_TO_INDEX()
宏的目的是返回一个从0到9的索引值。
问题是,当c
在a
和z
之间或(我想)在A
和Z
之间时,您使用它来获得从0到25的数字。
举例:c
为r
, (int)'r' - (int)'0')
为114 - 48 = 66
。因此,您尝试访问只有26个插槽的children
的66号插槽。
要纠正这个问题,可以这样重写CHAR_TO_INDEX()
#define CHAR_TO_INDEX(c) (c - (int)'a')
并以这种方式调用
index = CHAR_TO_INDEX( std::tolower( s[level] ) );
但我认为这是一个坏主意,使用宏,所以我建议你定义一个简单的函数与一些检查;像这样
int charToIndec (int ch)
{
if ( (ch < int(`a`)) || (ch > int(`z`)) )
; // throw something
return ch - int(`a`);
}
其他建议,没有特别的顺序…
你在用c++,而不是C;所以trienode
不需要typedef;你可以简单地写
struct trienode {
string definition; //For Definition of the word
bool isLeaf;
trienode *children[ALPHABET_SIZE];
};
并简单地使用结构体作为trienode
再次说明:您使用的是c++,而不是C;所以我不明白为什么你写一个函数getnode()
,应该是(IMHO) trienode
的构造函数;就像
trienode () : definition(""), isLeaf(false)
{
for ( int i = 0 ; i < ALPHABET_SIZE ; ++i )
children[i] = NULL;
}
应该这样使用
crawler->children[index]= new trienode;
在任何情况下,您已将ALPHABET_SIZE
定义为26;记住在任何地方使用它而不是26(当26是children
的维度时);将getnode()
中的26
替换为ALPHABET_SIZE
包括;bits/stdc++.h
是什么?我不知道,我甚至不知道它是不是c++标准的include。建议:使用标准包括。
最后一个建议:你使用new
节点;记住delete
分配的节点;如果您可以使用c++ 11编译器,请考虑使用std::unique_ptr
来避免这种需要。
注。