C++ 二维数组到一维数组 [英] C++ 2D array to 1D array
问题描述
我正在尝试将二维数组转换为一维数组.我对 C/C++ 非常陌生,但我认为学习如何将 2D 数组转换为 1D 非常重要.所以我在这里遇到了这个问题.
I am attempting to convert a 2D array to 1D. I'm extremely new to C/C++ but I think it's very important to learn how to convert a 2D array to 1D. So here I am stumbling upon this problem.
到目前为止我的代码是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;
}
我在我认为我失败的地方写了一条评论.
I wrote a comment at where I think I fail.
我还必须将进入 1D 的数字限制为 value^2 大于 50 的数字.但可以肯定的是,我必须解决转换 2D=>1D 的问题你能帮我吗?
I must also limit the numbers that get into the 1D to numbers who's value^2 is greater than 50. But for sure I must solve the problem with the conversion 2D=>1D Can you help me out?
推荐答案
你的假设是对的:
循环应该是这样的:
for (q = 0; q < n; q++)
{
for (t = 0; t < m; t++)
{
b[q * m + t] = a[q][t];
}
}
从更高维数组的角度考虑这种转换总是更容易.此外,对于您的代码,您实际上并未在 b
分配周期中修改 i
或 j
,因此您不应期望将不同的值分配给b
的不同数组成员.
It is always easier to consider such conversions from the view point of the higher dimension array. Furthermore with your code you did not actually modify i
or j
in the b
assigning cycle, so you should not expect different values to be assigned to the different array members of b
.
这篇关于C++ 二维数组到一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!