【问题标题】:Searching if an element exist in a queue c++搜索队列中是否存在元素c ++
【发布时间】:2020-03-14 04:00:49
【问题描述】:

所以我一直在尝试搜索用户输入的数字是否存在于队列中,如果存在则该函数将返回 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++ search queue


【解决方案1】:

只有你的第一个 cout 语句可能会被执行,其他的不会被执行,因为当你返回一些东西时,那是函数的结尾。也许在 return 之前移动 cout 语句,它应该可以工作。

此外,如果 array[i] != x 则不应返回 false,这仅表示 array[i] 不是您要查找的项目。也许您可以添加一个布尔变量 isFound 并仅在找到该值时将其设置为 true。如果你到了循环的末尾,但没有找到值(isFound == false),则返回 false。

【讨论】:

  • 非常感谢它终于奏效了,我明白了这个问题。我想问一下,我怎么知道函数是返回 true 还是返回 false,因为它没有出现在“我的意思是当你运行代码时”的输出中。对不起,我是初学者,我想完全了解操作。
  • 在你的主函数中你可以有一个像 cout
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-03
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2020-07-06
    相关资源
    最近更新 更多