如果用户从数组中输入数字,如何获取 2D 数组的索引

How do i get the index of a 2D array if the user enters a number from the array

本文关键字:数组 获取 2D 索引 何获取 用户 输入 数字 如果      更新时间:2023-10-16
#include<iostream>
using namespace std;
int main()
{
    int f[5][5], k = 1, n;
    for (int p = 0; p<5; p++)
    {
        cout << "Enter Elements Of Rows: " << k << endl;
        k++;
        for (int m = 0; m<5; m++)
        {
            cin >> f[p][m];//It take's rows as input
        }
    }
    //What should i do now because i can't understand how to print the index of n element.
    cout << "Enter the number you want to search:  ";
    cin >> n;
    //What should i do after this to get the index of the number n?
}

这段代码非常适合将行作为输入,但是当涉及到索引时,一切都会出错。搜索和工作了很多,但找不到任何东西。

如果您的意思是将 1D 索引转换为 2D 索引,那么这将可以:

int x = n % 5;
int y = n / 5;

假设这种格式:

0 1 2 3 4

5 6 7 8 9

9 10 11 12 13

14 15 16 17 18

19 20 21 22 23

然后通过以下方式访问它:

int result = f[x][y];

由于您没有任何关于元素可能在哪里的信息,因此我建议您进行线性搜索(意思是:查看每个元素并检查它是否是您正在寻找的元素(。

基本思想是你执行与已经完全相同的嵌套循环,但你执行检查而不是插入,如下所示:

...
...
cout << "Enter the number you want to search:  ";
cin >> n;
for (int p = 0; p<5; p++)
{
    for (int m = 0; m<5; m++)
    {
        if (f[p][m]==n){
          cout << "found " << n << " at " << p << " " << m << "n";
        } 
    }
}
...
...

这实际上只是非常基本的想法。

一些提示要考虑:

  • 您希望如何处理重复输入?(输出一次?你需要打破或标志(
  • 如果 2D 数组中没有这样的元素怎么办?(想说"未找到"之类的话...同样,需要一个标志。

我希望你能自己从这里继续。

改进代码的一些想法:

  • 参数化"5"。喜欢int d = 5.然后使用 d 初始化数组并脱离 for 循环。
  • 请注意,k与您的p密切相关。也许您可以随时使用p?我会让你弄清楚怎么做。

一个简单的暴力实现的考官:

#include<iostream>
#include<vector>
#include<utility>
using namespace std;
int main()
{
    int f[5][5], k = 1, n;
    for (int p = 0; p<5; p++)
    {
        cout << "Enter Elements Of Rows: " << k << endl;
        k++;
        for (int m = 0; m<5; m++)
        {
            cin >> f[p][m];//It take's rows as input
        }
    }
    cout << "Enter the number you want to search:  ";
    cin >> n;
    vector<pair<int, int> > result;
    for (int p = 0; p<5; p++)
    {
        for (int m = 0; m<5; m++)
        {
            if (n == f[p][m]) result.push_back(pair<int, int>(p, m));
        }
    }
    cout << "Search results:" << endl;
    for (std::vector<std::pair<int, int> >::iterator it = result.begin(); it != result.end(); it++)
    {
        cout << "[" << it->first << "][" << it->second << "]" << endl;
    }
    return 0;
}