【问题标题】:Bool method returns wrong valueBool 方法返回错误值
【发布时间】:2016-02-01 05:09:25
【问题描述】:

我为链表哈希表创建了一个bool contains(string) 方法,该方法检查值是否在哈希中。我使用辅助函数进行递归,但是当辅助函数返回 false 时,bool contains(string) 仍然返回 true。我通过调试器运行它,我可以清楚地看到它返回 false,我不知道为什么。

这是正在搜索的当前节点:

"laccoliths"->"morbiferous"->"oculi"->"unscabbarded"

我要搜索的值是"typung"

代码如下:

bool contains_h(string x, node * p) //helper method
{
    if (p == NULL)
        return false;
    else if (x == p->data)
        return true;
    else
        contains_h(x, p->next);
}

bool contains(string word) { return contains_h(word, head); }

【问题讨论】:

  • 启用编译器警告(并阅读它们)可以防止这个错误。

标签: c++ boolean return-value boolean-logic boolean-expression


【解决方案1】:

很简单的一个。你忘了把'return'放在最后的声明中:

bool contains_h(string x, node * p) //helper method
{
    if (p == NULL)
        return false;
    else if (x == p->data)
        return true;
    else
        return contains_h(x, p->next);
}


出于好奇,我将您的代码重写为单行代码,看看它会是什么样子:
bool contains_h(string x, node * p) //helper method
{
    return ((p!=NULL) && (x == p->data || contains_h(x, p->next)));
}

就个人而言,我更喜欢阅读您的六行。但是,其他人可能不同意,特别是因为它可以避免缺少返回语句的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2020-08-10
    • 1970-01-01
    • 2013-11-11
    • 2019-07-08
    • 2023-04-02
    • 2016-05-27
    • 2015-06-30
    相关资源
    最近更新 更多