用1个循环说明2D数组迭代 [英] Explain 2D array iteration with 1 loop
问题描述
有人可以解释为什么此算法可以将2D数组迭代为1D数组吗?换句话说,..有一个循环吗?
Can someone explain why this algorithm works for iterating a 2D array as a 1D array? In other words.. with one loop?
const int Width = 6;
const int Height = 4;
int Array[Width][Height];
for (int I = 0; I < Width * Height; ++I)
{
Array[I % Width][I / Width] = I; //This line :S
}
for (int I = 0; I < Height; ++I)
{
for (int J = 0; J < Width; ++J)
{
std::cout<<Array[J][I]<<" ";
}
std::cout<<"\n";
}
推荐答案
最简单的方法它的作用是自己插入数字。从0开始,我们将得到:
The easiest way to see how it works is to plug in the numbers yourself. Starting from 0, we'll get:
Array[0 % 6][0 / 6] = Array[0][0]
Array[1 % 6][1 / 6] = Array[1][0]
...
Array[5 % 6][5 / 6] = Array[5][0]
Array[6 % 6][6 / 6] = Array[0][1]
...
Array[11 % 6][11 / 6] = Array[5][1]
等。因为它使用整数除法,所以每次我们通过 Width
值时,它的 i / Width
都会多一个。利用 i%宽度
,它将以那个特定的 i /宽度$ c遍历每个值(在这种情况下为0到5)。 $ c>。因为整数除法会被截断,所以直到
i
成为 Width
的下一个倍数之前,这将是相同的。
and so on. Because it uses integer division, each time we go through Width
values, it i / Width
will be one more. Utilizing i % Width
, this will then loop over each value (in this case, 0 to 5) at that specific i / Width
. Because integer division truncates, this will be the same until i
becomes the next multiple of Width
.
这篇关于用1个循环说明2D数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!