c++ - 在 C++ 中实现一个 trie

标签 c++ data-structures trie

我想在 cpp 中实现一个 trie。当我尝试打印出 trie 中的所有字符串时,没有打印任何内容。但是代码编译成功。我认为我的插入有问题。我的猜测是我应该在某处通过引用传递,以便实际修改特里树,但我不确定问题出在哪里或出在哪里。

我的结构:

struct Node {
    unordered_map<char, Node*> children;
    bool completeWord;
};

class Trie {
private:
    Node* root;
    void printAll(Node* tmp);
public:
    Trie();
    void insert(string s);
    void printAll();
};

Trie::Trie() {
    root = new Node();
    root->completeWord = false;
}


方法:
void Trie::insert(string s) {
    Node* p = root;
    for(char c : s) {
        auto m = p->children;
        if(!m.count(c)) {
            Node* n = new Node();
            m.insert(pair<char, Node*>(c,n));
        }
        else
            p = m[c];
    }
    p->completeWord = true;
}


printAll 用于调试:
void Trie::printAll() {
    printAll(root);
}

void Trie::printAll(Node* tmp) {
    Node* t = tmp;
    auto m = t->children;
    if(!m.empty()){
        for(auto p : m) {
            cout << p.first << " ";
            printAll(p.second); 
        }
    }
}

测试用例:

int main() {
    Trie* t = new Trie();
    string arr[] = {"abc", "abcd", "lmn", "edf"};
    for(string s : arr) 
        t->insert(s);
    t->printAll();
    return 0;
}

最佳答案

感谢@Hitobat 和@Code-Apprentice,我知道我做错了什么。在我的 insert它应该是:

void Trie::insert(string s) {
    Node* p = root;
    for(char c : s) {
        auto &m = p->children; //m -> &m
        if(!m.count(c)) {
            Node* n = new Node();
            m.insert(pair<char, Node*>(c,n));
        }
        p = m[c]; //remove else
    }
    p->completeWord = true;
}
m之前只是指向映射对的指针,没有 &它只会更改这些对的拷贝,而不是这些对本身。所以我需要通过引用传递它们。
p插入新节点时未更新。

关于c++ - 在 C++ 中实现一个 trie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60644033/

相关文章:

c# - 如何从方法返回匿名类型?

java - 如何用Java打印Trie树?

performance - 将 Trie 编码为文件以避免重建

c++ - 为什么使用 argc 和 argv 时没有出现段错误?

c++ - 如何使用 VS Debugger 找出模板参数的类型?

c++ - 带字符串检查的哈希表

java - 将 Clojure 数据结构转换为 Java 集合

c++ - 对象的动态数组 - 初始化方法之间的区别

java - 具有高效查询算法的层次数据结构

java - Trie——Java 中的实现