Ant*_*nov 5 c++ arrays multidimensional-array
我正在尝试将2D数组转换为1D。我是C / C ++的新手,但我认为学习如何将2D数组转换为1D非常重要。因此,我在这里绊倒了这个问题。
到目前为止,我的代码是 http://ideone.com/zvjKwP
#include<iostream>
using namespace std;
int main()
{
int n=0,m=0; // 2D array nRow, nCol
int a[n][m];
int i,j; // ????? ????????? 2D
int q,p,t; // for 2D=>1D
int b[100];
int r; // for cout
cout<<"Enter the array's number of rows and columns: ";
cin>>n>>m;
// entering values for the 2D array
for (i = 0;i<=n;i++)
{
for (j = 0;j<=m;j++)
{
cout<<"a["<<i<<"]["<<j<<"]="<<endl;
cin>>a[i][j];
cin.ignore();
}
}
// Most likely the failzone IMO
for (q = 0;q<=i;q++)
{
for (t = 0;t<=i*j+j;t++)
{
b[t] = a[i][j];
}
}
// attempting to print the 1D values
cout<<"The values in the array are"<<"\n";
for(r=0;r<=t;r++)
{
cout<<"b["<<r<<"] = "<<b[r]<<endl;
}
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在我认为失败的地方发表了评论。
我还必须将进入一维的数字限制为value ^ 2大于50的数字。但是可以肯定的是,我必须通过转换2D => 1D来解决问题。您能帮帮我吗?
你的假设是对的:
循环应该是这样的:
for (q = 0; q < n; q++)
{
for (t = 0; t < m; t++)
{
b[q * m + t] = a[q][t];
}
}
Run Code Online (Sandbox Code Playgroud)
从更高维数组的角度考虑这种转换总是更容易。此外,对于您的代码,您实际上并未修改i或j在b分配周期中,因此您不应期望将不同的值分配给b.
http://www.cplusplus.com/doc/tutorial/arrays/
在该链接中查看伪多维数组部分。
我已经看到很多例子表明下标算法是错误的。如有疑问,请追查。二维数组的下标顺序应该从 0-(HEIGHT*WIDTH-1) 开始
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT * WIDTH];
int n,m;
int main ()
{
for (n=0; n<HEIGHT; n++)
for (m=0; m<WIDTH; m++)
{
jimmy[n*WIDTH+m]=(n+1)*(m+1);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29941 次 |
| 最近记录: |