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

时间:2017-01-12 20:31:07

标签: c++

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

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;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

你在搜索列表时犯了经典的新手错误,将“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;
}

答案 1 :(得分:1)

您的示例不会迭代,它仅报告第一个节点是否与t匹配。当openList为空时,永远不会输入for循环。请注意,如果未输入循环,则在函数结束之前不会遇到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_ifrange-based for loop

#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;
}