In my code, I've using a 2D multidimensional array to represent a grid (not always of equal sizes, eg 10x15 or 21x7). After reading about how jagged arrays are faster and are generally considered better, I decided I would change my 2D array into a jagged array.
This is how I declared the multidimensional array:
int[,] array = new int[10, 10];
I'm trying to figure out how to declare and then initialise the same thing, but using jagged arrays.
Edit This code is inside a class, and in the constructor I already have:
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];
}
}
}
}
And in another method I'm simply doing:
Console.WriteLine(grid.GetXY(5, 5).ToString());
Error message I'm getting:
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
What am I doing wrong and how should I be doing it?
Since you're dealing with one-dimensional arrays, you can simply use the Length Property to get the length of the first dimension:
int[][] grid = new int[10][];
for (int x = 0; x < grid.Length; x++)
{
grid[x] = new int[10];
}
(Using the GetLength Method works as well:)
int[][] grid = new int[10][];
for (int x = 0; x < grid.GetLength(0); x++)
{
grid[x] = new int[10];
}
The problem with your code is that you're calling grid.GetUpperBound(1)
where grid
is a one-dimensional array -- it doesn't have a second dimension (index 1) that you could get the upper bound of.
Your GetXY method should look like this:
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];
}
Note that jagged arrays are not magic that makes your code faster – measure if they actually do!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.