首页 > 解决方案 > 搜索队列中是否存在元素c ++

问题描述

因此,我一直在尝试搜索用户输入的数字是否存在于队列中,如果存在,则该函数将返回 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"; } 
         }
    } 

标签: c++searchqueue

解决方案


您应该改进缩进以查看程序的流程。此外,您应该知道 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";
        }
    }
} 

推荐阅读