c++ - Trie 中没有名为 children 的成员的运行时错误,即使在 Trie 类中明确定义了子项
问题描述
嗨,我是 C++ 的初学者,试图实现基本的 trie 结构。有人请帮忙。欢迎任何反馈。我收到运行时错误
Line 15: Char 25: error: no member named 'children' in 'Trie'
if(present->children[word[i]-'a']==NULL)
在过去的两天里,我一直试图解决这个问题。还是不知道。
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
string val="";
Trie* children[26];
bool flag=false;
}
Trie* root=new Trie();
/** Inserts a word into the trie. */
void insert(string word) {
Trie* present=root;
for(int i=0;i<word.size();i++)
{
if(present->children[word[i]-'a']==NULL)
{
Trie* p=new Trie();
p->val=present->val+word[i];
present->children[word[i]-'a']=p;
present=p;
}
else
present=present->children[word[i]-'a'];
w}
present->flag=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* present=root;
for(int i=0;i<word.size();i++)
{
if(present->children[word[i]-'a']==NULL)
return false;
else
present=present->children[word[i]-'a'];
}
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* present=root;
for(int i=0;i<word.size();i++)
{
if(present->children[word[i]-'a']==NULL)
return false;
else
present=present->children[word[i]-'a'];
}
for(int i=0;i<26;i++)
{
if(present->children[i]!=NULL)
return true;
}
return false;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
解决方案
在这个构造函数中
Trie() {
string val="";
Trie* children[26];
bool flag=false;
}
您创建了一个本地数组,该数组children
在构造函数之外不存在且不可见。
该类只有一个数据成员
Trie* root=new Trie();
可以在类的成员函数内部访问。
您需要设计一个数据结构来表示 trie 的一个节点,然后数据结构 trie 本身将包含一个或指向表示节点的数据结构的指针。
推荐阅读
- c# - 我想要用户的 ax value(double)。但是当试图输入 string.program 时崩溃。我该如何解决
- python - 生成趋势特定数据
- python - 如何用最短到最长匹配从头到尾替换文本
- rest - 捕获从 Restful 服务发送的数据包
- matlab - 为什么我的分类数组时间中的年份没有在 Matlab 中正确转换?
- asp.net - 无法在 Quickbooks 桌面版 Invoice 的 Other1 和 Other2 列中添加数据
- r - 使用 tidyr 计算文本挖掘中字符串的比例时遇到问题
- qt - QT + OpenCV undefiend 对 cv::stereoBM::create(int,int) 的引用
- debian - 得到()没有道歉
- php - Laravel Nova:存储相关文件记录的外键(包含文件路径)