因此,我一直在尝试搜索用户输入的数字是否确实存在于队列中,如果确实存在,则该函数将返回true,否则返回false。但是,无论我尝试哪种方法,它都无效:
bool cqueue::search(int x){ //this is my class cqueue
if(empty()) { cout<<"\n\n queue is empty\n"; }
for(int i=0;i<size;i++){
if(array[i]==x){
return true; cout<<x<<" is in the queue \n"; break; }
else {
return false; cout<<x<<" is not in the queue \n"; }
}
}
仅可能执行第一个cout语句,而其他第一个cout语句则不会执行,因为当您返回某些内容时,函数的结尾即告结束。也许将cout语句移到返回之前,它应该可以工作。
此外,如果array [i]!= x,则不应返回false,这仅意味着array [i]不是您要查找的项目。也许您可以添加一个布尔变量isFound,并且仅在找到该值时才将其设置为true。如果到达循环末尾,但找不到值(isFound == false),则返回false。
您应该改进缩进以查看程序的流程。另外,您应该知道return语句之后的任何内容都不会执行,因为return会“退出”该函数。就像其他人说的那样,如果对第一个元素的检查失败,则该函数以return false退出;这意味着将不进行其他检查。
bool cqueue::search(int x)
{ //this is my class cqueue
if(empty())
cout<<"\n\n queue is empty\n";
for(int i=0;i<size;i++)
{
if(array[i]==x)
{
return true;
cout<<x<<" is in the queue \n";
break;
}
else
{
return false;
cout<<x<<" is not in the queue \n";
}
}
}