不需要的输出重复和矩阵搜索问题
Unwanted output repetition and matrix search issues
此代码尝试在 5x5 矩阵中搜索目标值(项目),我将值硬编码到其中。它查询用户以获取要搜索的值。问题是,当我运行代码时,它会告诉我"找到项目!",而不管用户输入如何。此外,它似乎在重复用户输入。例如,当我使用"87"作为用户输入时,这是我的输出:
您要搜索的值是什么? 878787找到商品!
我对C++相当陌生,所以如果我做了一些愚蠢的事情,请原谅我。代码如下:
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
int target;
int flag;
int mat[5][5]= //hardcoded the matrix data
{
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
{21,22,23,24,25}
};
cout<<"What is the value you'd like to search for? ";
cin>>target;
for(int x=0;x<5;x++)
{
for(int y=0;y<5;y++)
{
if (mat[x][y]==target)
{
flag=1;
break;
}
else
{
//do nothing
}
}
}
if(flag == 1)
{
cout<<"Item found!";
}
else
{
cout<<"Item not found.";
}
return 0;
}
正如 aslg 在他的评论中提到的,你只打破你的内循环,你也需要喙外for(int x=0;x<5;x++)
循环。您可以在内部循环之后通过声明来执行此操作:
if(flag==0){
break;
}
但这并不是一个特别优雅的解决方案。我建议你让标准库来完成这项工作。
int* end = mat[0]+25;
int* found = std::find(mat[0],end,target);
if(found!=end)
{
cout<<"Item found!";
}
else
{
cout<<"Item not found.";
}
这里发生了什么:实际上,静态多维 5x5 数组存储为大小为 25 的一维数组。 mat[0]
指向它的开始,mat[0] + 25
指向它的结束。 std::find(start,end,target)
返回指向目标的指针,如果可以在 [start,end[] 中找到,否则返回end
。
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 这是一个二叉搜索树吗?黑客排名问题
- Sinlge 链表,C++,删除所有和搜索功能的问题
- 插入操作的二叉搜索树代码问题
- 我的模板二叉搜索树类给出了错误"Node<T>: no appropriate default constructor available,"如何解决这个问题?
- 如何使用C 中的广度优先搜索解决8个式嘴问题
- CTC梁搜索和TensorFlow C API的问题
- 如何使用二叉搜索树的索引生成器解决此问题
- 错误 C2676;在C++的二叉搜索树类中定义 ++ 运算符时遇到问题
- 在二叉搜索树中插入时出现问题
- C++数组长度的二进制搜索问题
- Qt C++macOS问题。我正在使用函数 .find( "a word") 在多集中搜索单词,它适用于 Windows 但不适用于 mac
- 二叉搜索树插入数据问题
- 二叉搜索树析构函数问题
- 我的二叉搜索树插入逻辑有什么问题?
- 如何在C 中解决线性搜索问题
- 不需要的输出重复和矩阵搜索问题
- 广度优先搜索问题c++