获取错误:警告C4715::并非所有控制路径都返回值,但不确定原因

Getting a Error : warning C4715: : not all control paths return a value but unsure why

本文关键字:返回值 不确定 路径 C4715 警告 取错误 获取 控制      更新时间:2023-10-16

所以我有一个搜索,它告诉我一个值是否在列表中,但它会给我这个错误,不确定为什么?

bool find(pNode* t, deque<unique_ptr<pNode>>& openList)
{
for (auto p = openList.begin(); p != openList.end(); p++) 
{
if (t->x == (*p)->x && t->y == (*p)->y)
{
cout << "The coords searched for are in the open list" << endl;
return true;
}
else
{
return false;
}
}
}

您的示例不进行迭代,它只报告第一个节点是否与t匹配。当openList为空时,永远不会输入for循环。请注意,如果未输入循环,则在函数结束之前不会遇到return语句。您可能想将return false语句放在循环之外,这样就解决了所有这些问题,并为您提供了预期的行为。此外,在这种情况下,openList应该是常量。

bool find(pNode* t, const deque<unique_ptr<pNode>>& openList)
{
for (auto p = openList.begin(); p != openList.end(); p++) 
{
if (t->x == (*p)->x && t->y == (*p)->y)
{
cout << "The coords searched for are in the open list" << endl;
return true;
}
}
return false;
}

请考虑使用std::find_if或基于范围的for循环。

#include <algorithm>
bool find(pNode* t, deque<unique_ptr<pNode>>& openList)
{
auto iter = std::find_if(openList.begin(), openList.end(), 
[t](const unique_ptr<pNode> & p_Ptr){
return p_Ptr->x == t->x && p_Ptr->y == t->y;
});
return iter != openList.end();
}

bool find(pNode* t, const deque<unique_ptr<pNode>>& openList)
{
for (auto && ptr : openList) {
if (t->x == ptr->x && t->y == ptr->y) {
return true;
}
}
return false;
}

在搜索列表时,您犯了一个典型的新手错误,将"false"结果放在循环中的else子句中。直到你完成循环,而不是在一次测试失败后,你才能判断出有什么东西没有找到。

bool find(pNode* t, deque<unique_ptr<pNode>>& openList)
{
for (auto p = openList.begin(); p != openList.end(); p++) 
{
if (t->x == (*p)->x && t->y == (*p)->y)
{
cout << "The coords searched for are in the open list" << endl;
return true;
}
}
return false;
}