gpt4 book ai didi

C++字典特里实现

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:41 26 4
gpt4 key购买 nike

我在 insert 函数中遇到段错误:

current->isWord = true;

一切都可以正常编译,没有警告或错误 (g++ -Wall -Wextra)。我的 main 函数只调用了一次 insert 函数,但它不起作用。这是我的代码;它是我的 .h.cpp 文件的混合体:

const int alphabetSize = 26;

struct Node
{
bool isWord;
Node* child[alphabetSize];
};

Dictionary::Dictionary()
{
initNode(head); //Node* head; is defined in my .h file under private:
}

bool Dictionary::isPrefix(string s)
{
Node* current = endOfString(s, false);
if (current == NULL)
{
return false;
}
else
{
return true;
}
}

bool Dictionary::isWord(string s)
{
Node* current = endOfString(s, false);
if (current == NULL)
{
return false;
}
else
{
return current->isWord;
}
}

void Dictionary::insert(string s)
{
Node* current = endOfString(s, true);
current->isWord = true; //segfault here
}

//initializes a new Node
void Dictionary::initNode(Node* current)
{
current = new Node;
current->isWord = false;
for (int i = 0; i < alphabetSize; i++)
{
current->child[i] = NULL;
}
}

//returns a pointer to the Node of the last character in the string
//isInsert tells it whether it needs to initialize new Nodes
Node* Dictionary::endOfString(string s, bool isInsert)
{
Node* current = head;
Node* next = head;
for (unsigned int i = 0; i < s.length(); i++)
{
if (isalpha(s[i]) == true)
{
int letter = (tolower(s[i]) - 'a');
next = current->child[letter];
if (next == NULL)
{
if (isInsert == false)
{
return NULL;
}

initNode(next);
current->child[letter] = next;
}
current = current->child[letter];
}
}

return current;
}

最佳答案

initNode 创建一个新的 Node 并初始化它,但它随后被丢弃。因为 current 是按值传递的,所以当它在函数内部被修改时,更改不会传播到 initNode 之外。直接的解决方法是让它通过引用传递:

void Dictionary::initNode(Node*& current)

关于C++字典特里实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892922/

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