c++ - 搜索队列中是否存在元素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"; }
}
}
解决方案
您应该改进缩进以查看程序的流程。此外,您应该知道 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";
}
}
}
推荐阅读
- powerbi - 如何通过在 PowerBI 上从昨天相同的表值中减去今天的表值来创建新表并为差异值提供颜色编码?
- c++ - 使用三数比较器进行排序
- java - 尽可能基本地重写终端中的内容(JAVA)
- python - Pyspark在将数据帧行转换为字典时保留字段的顺序
- mapbox - 不能排除 mapbox 路线上的渡轮、收费站或高速公路
- api - net core api 是否检查每个请求的 jwt 到期日期?
- c - 在 C 中向 TCP 连接的客户端发送 UDP 消息
- python - Amazon Elastic Inference 客户端库日志记录
- flutter - 颤振有没有一种正确的方法来实现 BLoC?
- spring - 在spring mvc中提交响应后无法创建会话