如果用户从数组中输入数字,如何获取 2D 数组的索引
How do i get the index of a 2D array if the user enters a number from the array
#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;
}
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 使用指针从C++中的数组中获取最大值
- 获取字符串的长度并将其分配给数组
- 数组长度,为什么从命令行获取时不能使用它?
- 如何在 nlohmann 的 json 库中获取数组长度?
- 在c++中获取两个大int,并将它们存储在数组中
- 如何在C++中获取二维数组中最少的一列数?
- 从 numpy 数组获取指针以将图像发送到C++
- 指针数组.获取指针元素的值
- 循环以使用 cstring 数组 c++ 获取用户输入
- 一种从元组/数组获取参数包的方法
- 如何使用数组获取输入,并将其存储在record.h类的主类中的变量中
- 如何使用数组获取命令行参数
- 从 JSON 数组获取天气
- 布尔数组获取意外的默认值
- 填充列表<>使用数组获取错误的数字
- 如何在C++中为矢量数据结构中的二维数组获取用户输入,而不使用行和列上的两个for循环
- 在自定义库中操作2d C++数组-获取行数
- 使用数组获取测试结果
- 数组c++获取值