不需要的输出重复和矩阵搜索问题

Unwanted output repetition and matrix search issues

本文关键字:搜索 问题 输出 不需要      更新时间:2023-10-16

此代码尝试在 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