C ++ trie返回错误的节点属性

时间:2014-01-30 14:24:06

标签: c++ pointers indexing trie

我有一个来自类的trie,我在节点结构中添加了一个属性(pb_entry)。

trie必须存储电话号码,并且应该在搜索后返回pb_entry。

int main()一样,我添加了电话号码“123456”,我说它已存储(pb_entry中的值)为42.我添加了另一个号码“9101112”,它存储在33

如果我搜索“123456”,则返回值33,但这是9101112的值。

抱歉,伙计们,我有点困惑。谢谢你的帮助。

#include <iostream>
#include <cctype>

#define deep 10

class PBTrie
{
public:
struct Node
{
    Node() : final(false)
    {
        for(int i = 0;i < deep;++i) {
        children[i] = 0;

        }
    }

    ~Node()
    {
        for(int i = 0;i < deep;++i) {
            if(children[i]) delete children[i];
        }
    }

    Node*& child(char c)
    {
        return children[c];
    }

    Node* children[deep];
    int pb_entry;
    bool final;
};

PBTrie()
{
    root = new Node;
}

~PBTrie()
{
    delete root;
}

void add(std::string word, int entry) {
    Node* curr = root;
    for(int i = 0;i < word.length();++i)
    {
        char& c = word[i];
        if(!isalpha(c)) {
            continue;
        }
        if(!curr->child(c)) {
            curr->child(c) = new Node;
        }
        curr = curr->child(c);
    }
    curr->pb_entry = entry;
    std::cout << "ADDED pb_entry: " << curr->pb_entry << std::endl; //debug cout
    curr->final = true;
}

int search(std::string word)
{
Node* curr = root;
for(int i = 0;i < word.size();++i)
{
    char& c = word[i];
    if(!isalpha(c)) {
        continue;
    }
    if(!curr->child(c))
    {
        return -2;
    }
    curr = curr->child(c);
}
return curr->pb_entry;
}

private:
    Node* root;
};

int main() {
PBTrie trie;
trie.add("123456",42);
trie.add("9101112",33);
std::cout << trie.search("123456") << std::endl;

}

输出:

ADDED pb_entry: 42
ADDED pb_entry: 33
33

0 个答案:

没有答案