执行尝试树时出错
Error Executing Trie Tree
我想插入一个字符串,并使用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
。它将一个默认构造的对象插入到容器中,并返回对它的引用。为了检查是否存在键,请使用find
或count
。
4.
trie* node = current->child[ch];
if (node == NULL) {
trie* node = newtrienode();
current->child.insert(pair<char, trie>(ch, node));
}
current = node;
请注意,在第三行中,您正在声明一个新变量。第一行中声明的变量node
不会被更改。
相关文章:
- 执行时使用 boost::asio::d eadline_timer 时出错
- 尝试在Windows上执行C++时出错(通过MinGW编译)
- 在另一台 PC 上执行程序时加载 SDL2 共享库时出错
- 在 C/C++ 中使用 MySQL 连接器执行插入到表时出错
- 从 Qt(release) 生成的文件执行.EXE文件时出错
- 在 Qt 中将 x 可执行文件作为按钮事件运行时出错
- g++:尝试执行"jc1"时出错:execvp:没有这样的文件或目录
- 在返回另一个函数的函数中执行程序期间出错
- 可执行文件在运行时出错
- 将 CLANG 构建的可执行文件与 G++-v6 构建的 Boost 库链接时出错
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- 执行 C++ 代码后出错
- 执行尝试树时出错
- 编译后可执行文件出错
- 执行make时出错
- 在C++中使用popen执行perl命令时出错
- libGL 在执行 OpenGL 程序时出错
- "No such file or directory" 使用 makefile 时在 c++ 中执行简单 fstream 时出错
- 在 OpenCV 中执行特征面算法时出错
- 尝试查找执行"cc1d"时出错