【问题标题】:What am I missing with this failed, C++ string comparison?这个失败的 C++ 字符串比较我错过了什么?
【发布时间】:2020-04-17 02:50:09
【问题描述】:

我正在尝试将字符串与二叉搜索树进行比较,下面的代码在第一个搜索树上工作,但在其他所有搜索树上都失败了——即使我已经检查以确保它正在递归检查树.谢谢!

bool BST::compareIt(Node* current, string name)
{
    if (name == current->title)
       return true;
    if (current->left != NULL)
        compareIt(current->left, name);
    if (current->right != NULL)
        compareIt(current->right, name);
    return false;
 }

【问题讨论】:

  • 就我个人而言,我不喜欢使用字符串。我使用 char* 代替...
  • @mlwn 为什么会这样?字符串有什么问题?
  • 大多数时候,我为有限的处理器编写代码,并且我喜欢控制所使用的内存......我猜现代机器上的字符串没有问题
  • @mlwn 这很有趣,但不太可能帮助澄清这个问题或帮助这个问题的读者。
  • @aschepler ...我什至对你的评论投了赞成票...你是对的..

标签: c++ string binary-search-tree


【解决方案1】:

您需要返回递归调用的结果,例如

if (current->left != NULL)
    return compareIt(current->left, name);

同样适用于右手分支。

【讨论】:

  • 你是天赐之物。显而易见的东西在我面前,我没有看到它。感谢您指出!
  • 不用担心,每个人都会遇到。如果对您有用,请考虑接受答案。
猜你喜欢
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2023-04-03
  • 2012-03-12
  • 2015-04-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多