将一维数组的索引转换为二维数组

converting the index of 1D array into 2D array

本文关键字:二维数组 转换 索引 一维数组      更新时间:2023-10-16

如何将一维数组的索引转换为二维数组? 我知道如何将 2D 数组转换为 1D (i*the size of row+j).我想要相反的。

您需要知道的是: 2D 数组应该有多少列:假设你有一个 20 列和 10 行的数组(array[20,10]):

int index  = 47;
int numberOfColumns = 20;
int column = index % numberOfColumns;
int row    = index / numberOfColumns;
// column == 7
// row    == 2

你可以做相反的事情。 如果 n 是行的长度,x 是一维索引。您可以像

array[x/n][x%n]