C++ 这里有一个返回 (24) 的布尔返回类型函数

C++ There is a bool return type function returning (24) here

本文关键字:布尔 返回类型 函数 这里 有一个 返回 C++      更新时间:2023-10-16

首先对不起代码太多

这里有一个带有类型类的向量(teamNum(,该类包含一个带有类型结构的向量(播放器(,这有点复杂,但是在这个函数中,我需要检查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;
}
}
}

在主要

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

输出为 24 !!!! (请注意,当团队(Leverpool(是矢量团队中的最后一个团队时,就会发生这种情况(

再次抱歉代码太多,但我需要知道该错误,不仅解决了我需要向您学习的问题

您遇到了未定义的行为。

如果您在最后一个元素上采用if (teamNum[i].tName == _tname)-branch,但没有找到具有正确 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;
}

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