嗨:)有谁能告诉我为什么下面的代码不起作用吗?该程序在对应于'B'
的节点中的if(children[word[letter_no] - 'A'] == nullptr)
行处崩溃。但节点是创建的,当我尝试在构造函数中调用children[1]
时,它起作用。但是,当它被称为在insert()
功能,它不...试图插入一个单词到trie中时出现分段错误
包括
#include <memory> //shared_ptr
#include <string>
using namespace std;
const int ALPHABET = 26;
class Node {
public:
shared_ptr<Node> children[ALPHABET];
Node() { for (int i = 0; i < ALPHABET; ++i) children[i] = nullptr;}
void insert(const string &word, unsigned letter_no) {
if (letter_no < word.length()) {
if (children[word[letter_no] - 'A'] == nullptr)
children[word[letter_no] - 'A'] = make_shared<Node>();
children[word[letter_no] - 'A']->insert(word, letter_no+1);
}
}
};
int main() {
Node trie{};
trie.insert("ABC", 0);
return 0;
}
请注意,字母不授权是在一个连续范围相同的数字。如果例如系统使用了EBCDIC(可以),那么这将不起作用。 – NathanOliver
偏离主题,但空行和括号是免费的! – peval27