返回状态后,功能不会结束
Function does not end after return placed in condition
这里是节点定义:
Node::Node(int value, Node* left, Node* right) {
this->value = value;
this->left = left;
this->right = right;
}
int Node::getValue() const {
return value;
}
Node* Node::getLeft() const {
return left;
}
Node* Node::getRight() const {
return right;
}
这里的函数包含:
static bool contains(const Node& root, int value)
{
cout << "Root value: " << root.getValue() << endl;
if(root.getValue() == value)
{
cout << "You entered." << endl;
return true;
}
else if(root.getLeft() != NULL)
{
cout << "Left tree: " << endl;
contains(*(root.getLeft()), value);
}
else if(root.getRight() != NULL)
{
cout << "Right tree: " << endl;
contains(*(root.getRight()), value);
}
cout << "End" << endl;
return false;
}
现在我使用这个函数:
Node n1(1, NULL, NULL);
Node n3(3, NULL, NULL);
Node n2(2, &n1, &n3);
cout << "Contains? " << contains(n2, 1) << endl;
此 1 值位于左侧子树中。它显示"您输入了",无论如何都会转到显示 0 的函数末尾作为结果。为什么它不显示 1(true(?我错过了什么?
您缺少一些返回语句。
cout << "Root value: " << root.getValue() << endl;
if(root.getValue() == value)
{
cout << "You entered." << endl;
return true;
}
else if(root.getLeft() != NULL)
{
cout << "Left tree: " << endl;
contains(*(root.getLeft()), value); // no return here
}
else if(root.getRight() != NULL)
{
cout << "Right tree: " << endl;
contains(*(root.getRight()), value); // and no return here
}
cout << "End" << endl;
return false;
它检查树是否在某处包含值,但 nether 将结果传递给外部世界。将其更改为
if (root.getValue() == value)
{
cout << "You entered." << endl;
return true;
}
auto left = root.getLeft();
if (left)
{
cout << "Checking Left tree: " << endl;
if (contains(*left, value))
return true;
}
auto right = root.getRight();
if (right)
{
cout << "Checking Right tree: " << endl;
if (contains(*right, value))
return true;
}
cout << "End" << endl;
return false;
它应该有效。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 为什么在这个代码结束循环中没有得到结束
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 返回状态后,功能不会结束
- 在意外功能结束时进行清理,标准等效
- C 功能:读取直到文件结束 - 查找代码中的错误
- 如何结束此功能?(C++)
- ADL和容器功能(开始,结束等)
- 关于检查游戏是否结束的2048年游戏的功能
- 用QT中的按钮结束功能
- 功能结束后的 SEG 故障 (C++)
- 控制达到非空功能结束.我该如何解决这个问题
- 警告:控制达到非无效功能结束 - Qt应用程序
- 控制已结束非无效功能