C++ 如果用户从数组中输入数字,如何获取2D数组的索引 #包括 使用名称空间std; int main() { int f[5][5],k=1,n; 对于(int p=0;p
如果您的意思是将1D索引转换为2D索引,则可以:C++ 如果用户从数组中输入数字,如何获取2D数组的索引 #包括 使用名称空间std; int main() { int f[5][5],k=1,n; 对于(int p=0;p,c++,arrays,C++,Arrays,如果您的意思是将1D索引转换为2D索引,则可以: #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
#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?
}
采用这种格式:
01 2 3 4
56789
91011213
1415161718
19202223
然后通过以下方式访问它:
int x = n % 5;
int y = n / 5;
因为您没有关于元素可能在哪里的任何信息,所以我建议您只进行线性搜索(意思是:查看每个元素并检查它是否是您要查找的元素) 其基本思想是,执行与之前完全相同的嵌套循环,但执行检查而不是插入,如下所示:
int result = f[x][y];
。。。
...
cout>n;
对于(int p=0;p简单暴力实现的示例:
...
...
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";
}
}
}
...
...
#包括
#包括
#包括
使用名称空间std;
int main()
{
int f[5][5],k=1,n;
对于(int p=0;p请修复你的indentation.TIA。你有关于如何在2d数组中搜索的代码吗?伙计,对任何答案有任何反馈吗?评论、投票等等?这些答案都没有帮助你实现你想要的吗?
#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;
}