C ++ 2D数组到1D数组 [英] C++ 2D array to 1D array
问题描述
我正在尝试将2D数组转换为1D. 我是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
My code so far is 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.
我还必须将进入一维的数字限制为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 ++ 2D数组到1D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!