[英]Changing a 2D array to jagged array
在我的代碼中,我使用了2D多維數組來表示網格(並不總是具有相等的大小,例如10x15或21x7)。 在閱讀了鋸齒狀陣列如何更快並且通常被認為更好之后,我決定將2D陣列更改為鋸齒狀陣列。
這就是我聲明多維數組的方式:
int[,] array = new int[10, 10];
我試圖弄清楚如何聲明然后初始化同一件事,但使用鋸齒狀數組。
編輯此代碼在類內部,並且在構造函數中我已經具有:
class ProceduralGrid
{
private int[][] grid;
private int _columns;
private int _rows;
public ProceduralGrid(int rows, int columns)
{
_rows = rows; //For getters
_columns = columns;
//Create 2D grid
int x, y;
grid = new int[rows][];
for (x = 0; x < grid.Length; x++)
{
grid[x] = new int[10];
}
}
public int GetXY(int rows, int columns)
{
if (rows >= grid.GetUpperBound(0) + 1)
{
throw new ArgumentException("Passed X value (" + rows.ToString() +
") was greater than grid rows (" + grid.GetUpperBound(0).ToString() + ").");
}
else
{
if (columns >= grid.GetUpperBound(1) + 1)
{
throw new ArgumentException("Passed Y value (" + columns.ToString() +
") was greater than grid columns (" + grid.GetUpperBound(1).ToString() + ").");
}
else
{
return grid[rows][columns];
}
}
}
}
在另一種方法中,我只是在做:
Console.WriteLine(grid.GetXY(5, 5).ToString());
我收到錯誤消息:
Unhandled Exception: System.IndexOutOfRangeException: Array does not have that m
any dimensions.
at System.Array.GetUpperBound(Int32 dimension)
at ProcGen.ProceduralGrid.GetXY(Int32 rows, Int32 columns) in C:\Users\Lloyd\
documents\visual studio 2010\Projects\ProcGen\ProcGen\ProceduralGrid.cs:line 115
at ProcGen.Program.Main(String[] args) in C:\Users\Lloyd\documents\visual stu
dio 2010\Projects\ProcGen\ProcGen\Program.cs:line 27
我在做什么錯,應該怎么做?
由於要處理一維數組,因此可以簡單地使用Length屬性來獲取第一維的長度:
int[][] grid = new int[10][];
for (int x = 0; x < grid.Length; x++)
{
grid[x] = new int[10];
}
(使用GetLength方法也可以:)
int[][] grid = new int[10][];
for (int x = 0; x < grid.GetLength(0); x++)
{
grid[x] = new int[10];
}
代碼的問題在於,您正在調用grid.GetUpperBound(1)
,其中grid
是一維數組-它沒有第二個維度(索引1),可以獲取上限。
您的GetXY方法應如下所示:
public int GetXY(int x, int y)
{
if (x < 0 || x >= grid.Length)
{
throw ...
}
int[] items = grid[x];
if (y < 0 || y >= items.Length)
{
throw ...
}
return items[y];
}
請注意,鋸齒狀的數組並不是魔術,它可以使您的代碼更快-測量它們是否確實如此!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.