Trie实现的以下代码在调用函数insert时抛出浮点异常.for循环内部的行检查现有节点是问题所在.
struct Node {
char c;
bool isend;
unordered_map<int, struct Node*> map;
};
void insert(struct Node* root, string contact) {
int size = contact.size();
char ch;
for (int i = 0; i < size; i++) {
ch = contact[i];
// this check is creating problem
if (root->map.find(ch) == root->map.end()) {
struct Node* tmp = (struct Node*) malloc(sizeof(struct Node));
tmp->c = ch;
if (i == (size - 1)) {
tmp->isend = true;
} else {
tmp->isend = false;
}
root->map.insert(make_pair(ch, tmp));
root = tmp;
} else {
root = root->map[ch];
}
}
}
int main()
{
struct Node* root = NULL;
root = (struct Node*) malloc(sizeof(struct Node));
insert(root, "text");
}
Run Code Online (Sandbox Code Playgroud)
有帮助吗?
不要在C++代码中使用malloc(除非你真的知道你在做什么)
root = new Node;
Run Code Online (Sandbox Code Playgroud)
和
tmp = new Node;
Run Code Online (Sandbox Code Playgroud)
问题是,因为你使用malloc,构造函数Node::map不会被调用.使用new将确保调用所有必需的构造函数.