使用 trie 的 pset4 拼写器。尺寸函数的问题
pset4 speller using trie. Problem with the size function
我正在使用 trie 开发 pset4 拼写器。我想使用递归来查找加载的字典的大小。但没有任何效果。根据调试器正在做的事情,我认为它可能不会返回到 sizer 之前指向的位置。例如在 :
的字典中
a
aa
aab
ab
大小能读前三。但是当我将计数器恢复到以前的大小时,它不会读取 a 之后的字母 b。我认为它仍在检查正在读取 aab 的数组。我能做什么???
unsigned int size(void)
{
int ctr = 0;
for (int i = 0; i < N; i++)
{
if (sizer -> children[i] == NULL)
{
continue;
}
else
{
// do i need to use a pointer here to point
// to sizer before changing it
sizer = sizer -> children[i];
if ((sizer -> is_word) == true)
{
ctr ++;
}
int x = size();
ctr += x;
}
}
// Before returning ctr should i use the pointer to change sizer to
// what it was previously . Can it work???
return ctr;
}
I think it is still checking the array in which it is reading aab. what can i do ???
我认为你是对的。
考虑如何在这段代码中更新全局变量 sizer
的值。你这样做的唯一方法是:
sizer = sizer -> children[i];
因为你只设置 sizer
指向当前节点的一个子节点,从不将它恢复到以前的值,程序只遵循从根到叶的一条路径,然后它已经用尽了它的能力。通过不同的输入,您可以自己证明这就是正在发生的事情。例如,
a
b
ba
将报告计数为 1,因为它首先遍历节点 "a",并且它是一片叶子。
全局变量很容易给你带来麻烦,尤其是可修改的变量。现在开始培养避免使用它们的习惯。相反,更喜欢通过参数将信息传递给函数。
在大多数情况下也更愿意避免递归,甚至不考虑将递归与可修改的全局变量相结合,直到你有更多的经验(到那时会告诉你 "I want no part of that")。
不清楚 sizer
的类型是什么,但假设它是 struct sizer *
。在那种情况下,考虑将函数签名更改为
还需要进行哪些其他更改
unsigned int size(const struct sizer *node_sizer);
这不仅仅是一种风格。如果处理得当,它也会解决您的功能问题。
我正在使用 trie 开发 pset4 拼写器。我想使用递归来查找加载的字典的大小。但没有任何效果。根据调试器正在做的事情,我认为它可能不会返回到 sizer 之前指向的位置。例如在 :
的字典中a
aa
aab
ab
大小能读前三。但是当我将计数器恢复到以前的大小时,它不会读取 a 之后的字母 b。我认为它仍在检查正在读取 aab 的数组。我能做什么???
unsigned int size(void)
{
int ctr = 0;
for (int i = 0; i < N; i++)
{
if (sizer -> children[i] == NULL)
{
continue;
}
else
{
// do i need to use a pointer here to point
// to sizer before changing it
sizer = sizer -> children[i];
if ((sizer -> is_word) == true)
{
ctr ++;
}
int x = size();
ctr += x;
}
}
// Before returning ctr should i use the pointer to change sizer to
// what it was previously . Can it work???
return ctr;
}
I think it is still checking the array in which it is reading aab. what can i do ???
我认为你是对的。
考虑如何在这段代码中更新全局变量 sizer
的值。你这样做的唯一方法是:
sizer = sizer -> children[i];
因为你只设置 sizer
指向当前节点的一个子节点,从不将它恢复到以前的值,程序只遵循从根到叶的一条路径,然后它已经用尽了它的能力。通过不同的输入,您可以自己证明这就是正在发生的事情。例如,
a
b
ba
将报告计数为 1,因为它首先遍历节点 "a",并且它是一片叶子。
全局变量很容易给你带来麻烦,尤其是可修改的变量。现在开始培养避免使用它们的习惯。相反,更喜欢通过参数将信息传递给函数。
在大多数情况下也更愿意避免递归,甚至不考虑将递归与可修改的全局变量相结合,直到你有更多的经验(到那时会告诉你 "I want no part of that")。
不清楚 sizer
的类型是什么,但假设它是 struct sizer *
。在那种情况下,考虑将函数签名更改为
unsigned int size(const struct sizer *node_sizer);
这不仅仅是一种风格。如果处理得当,它也会解决您的功能问题。