thereIsSimilarID 函数中的错误导致意外返回值 (24)

问题描述 投票:0回答:1

对于冗长的代码,我深表歉意,但我在 C++ 程序中遇到了意外问题。我有一个类类型的向量 (

teamNum
),其中包含一个结构类型的向量 (
player
)。在
thereIsSimilarID
函数中,我的目标是检查
teamNum
中是否存在满足以下条件的玩家:
tName
等于
_tname
(函数参数)且
pID
等于
_pID
(函数参数) .

bool thereIsSimilarID(string _tname, int _pID)
{
    for (int i = 0; i < teamNum.size(); i++)
    {
        if (teamNum[i].tName == _tname)
        {
            for (int j = 0; j < teamNum[i].player.size(); j++)
            {
                if (teamNum[i].player[j].pID == _pID)
                    return true;
            }
        }
        else if (i == (teamNum.size() - 1))
        {
            return false;
        }
    }
}

main
功能中:

int main()
{
    cout << "\n" << thereIsSimilarID("Leverpool", 1) << endl;
}

意外输出为 24,并且仅当团队(“Leverpool”)是

teamNum
向量中的最后一个团队时,才会出现此问题。

如果您能提供有关识别和解决此错误的指导,我将不胜感激。此外,如果可能的话,请帮助我了解根本原因,以便我可以从解决方案中学习。谢谢您的协助!

c++ function boolean
1个回答
3
投票

您遇到了未定义的行为。

如果您在最后一个元素上采用

if (teamNum[i].tName == _tname)
分支,但找不到具有正确 pID 的玩家,则不会返回任何内容。这意味着,返回值是当前应保存返回值的内存位置中的任何随机值。在你的例子中,它发生在 24 点。但理论上,一切都可能发生。

teamNum
为空时也会出现同样的问题。

解决方案是确保始终从函数返回一个值(当然,除非它具有返回类型

void
):

bool thereIsSimilarID(string _tname, int _pID)
{
    for (int i = 0; i < teamNum.size(); i++)
    {
        // In this loop return true if you find a matching element
    }

    // If no matching element was found we reach this point and make sure to return a value
    return false;
}

您应该查看您的编译器设置并启用所有警告。通常最好让它将某些警告视为错误。

© www.soinside.com 2019 - 2024. All rights reserved.