gpt4 book ai didi

C++ 深度优先搜索带前缀参数的 Trie

转载 作者:太空狗 更新时间:2023-10-29 22:57:36 25 4
gpt4 key购买 nike

我正在尝试实现一个可以打印出具有给定前缀的单词频率的 trie。

编辑:感谢@kaidul-islam 发现我的错误并出现以下错误:

new_word->child[letter]->prefixes_++;

固定代码如下:

特里类:

class Trie
{
public:
Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
{
for (int i=0; i<26; i++)
{
child[i] = nullptr;
}
}
virtual ~Trie();

//Child nodes of characters from a-z
Trie *child[26];
//vector<Trie> child;

int prefixes_;

//accessor & mutator functions
bool GetIsLeaf() { return is_leaf_; }
void SetIsLeaf(bool val) { is_leaf_ = val; }
int GetFrequency() { return frequency_; }
void SetFrequency(int val) { frequency_ = val; }
int GetPrefixes() { return prefixes_; }
void SetPrefixes(int val) { prefixes_ = val; }
bool is_leaf_;

private:
//bool is_leaf_;
int frequency_;
};

问题中的函数:

void AddWord(string &word, Trie *root)
{
Trie *new_word = root;
new_word->prefixes_++;
for(unsigned int i = 0 ; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a'; //extract character of word
if(new_word->child[letter] == nullptr)
{
new_word->child[letter] = new Trie;
}

/*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
int x = (new_word->child[letter]->GetPrefixes())+1;
cout << "value of x: " << x << endl;
new_word->child[letter]->SetPrefixes(x);*/
new_word->child[letter]->prefixes_++;

new_word = new_word->child[letter];
}
new_word->SetFrequency(new_word->GetFrequency()+1);
/*
cout << "Word: " << word << endl;
cout << "frequency: " << new_word->GetFrequency() << endl;
cout << "prefixes: " << new_word->GetPrefixes() << endl;
cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
*/
}

最佳答案

经过快速检查,我发现您没有在构造函数中初始化成员变量。

Trie(): prefixes_(0),
is_leaf_(false),
frequency_(0) {

for(int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}

与全局变量不同,不能保证 prefixes_ 在声明时默认为 0。 child[i] 也不能保证是 nullptr。您需要初始化所有内容。

关于C++ 深度优先搜索带前缀参数的 Trie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43566989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com