执行尝试树时出错

Error Executing Trie Tree

本文关键字:出错 执行      更新时间:2023-10-16

我想插入一个字符串,并使用trie数据结构进行搜索。这是我第一次使用指针实现,所以我真的很困惑我在代码中做错了什么,它给出了编译错误。请帮助调试它,并告诉我指针逻辑中出了什么问题。

typedef struct trie {
unordered_multimap<char, struct trie> child;
bool isEnd;
} trie;
trie* newtrienode()
{
trie* newnode = (trie*)malloc(sizeof(trie));
newnode->isEnd = false;
return newnode;
}
trie* root = newtrienode();
void insert(string word)
{
trie* current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word[i];
trie* node = current->child[ch];
if (node == NULL) {
trie* node = newtrienode();
current->child.insert(pair<char, trie>(ch, node));
}
current = node;
}
current->isEnd = true;
}
bool search(string word)
{
trie* current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word[i];
trie* node = current->child[ch];
if (node == NULL) {
return false;
}
current = node;
}
return true;
}

除了注释中提到的内容外,我还看到了代码中的一些问题。

1.

trie* newnode = (trie*)malloc(sizeof(trie));

这不会创建类型为trie的对象,它只分配一个大小为trie的内存块,并将指向它的指针分配给变量newnode。特别是,它没有调用unordered_multimap的构造函数。通过该指针对child成员的任何访问都会产生未定义的行为。此外,你永远无法释放那段记忆。

2.

typedef struct trie {
unordered_multimap<char, struct trie> child;
bool isEnd;
} trie;

在第二行中,您将声明一个unordered_multimap数据成员,该成员的类型trie不完整,作为第二个模板参数。有些编译器允许这样做,但标准不要求它们这样做。另一方面,shared_ptr需要与不完整的类型作为模板参数一起使用。此外,一个节点每个字符只能有一个子树,因此不需要多映射;一张地图就足够了。所以我建议使用unordered_map<char, shared_ptr<trie>>,并用shared_ptr<trie>替换所有出现的trie*。一旦root发布,它还将负责删除对象。

newtrienode()函数如下所示:

shared_ptr<trie> newtrienode()
{
shared_ptr<trie> newnode (new trie());
newnode->isEnd = false;
return newnode;
}

3.

trie* node = current->child[ch];
if (node == NULL) {

当密钥不存在时,operator[]不返回NULL。它将一个默认构造的对象插入到容器中,并返回对它的引用。为了检查是否存在键,请使用findcount

4.

trie* node = current->child[ch];
if (node == NULL) {
trie* node = newtrienode();
current->child.insert(pair<char, trie>(ch, node));
}
current = node;

请注意,在第三行中,您正在声明一个新变量。第一行中声明的变量node不会被更改。