Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining two dimensional Dynamic Array

Tags:

arrays

c#

.net

How can I define two dimensional dynamic array? If I want to use List<>, can I use it for two dimensions?

like image 234
Harikrishna Avatar asked Dec 21 '09 10:12

Harikrishna


People also ask

Can we allocate a 2 dimensional array dynamically?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

How do you define two-dimensional array?

A one-dimensional array can be seen as data elements organised in a row. A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. Many games use two dimensional arrays to plot the visual environment of a game.

Which function is used to created dynamic 2D arrays?

The malloc() function is used in c programming to store the data in the heap which is dynamic memory storage. It is mostly used for the dynamic declaration of the arrays and also be used for the creation of two-dimensional arrays.


1 Answers

There's no built-in dynamic equivalent of two-dimensional arrays that I'm aware of, but you can easily get at more or less the same functionaltiy.

Define a Coordinate class with this API:

public class Coordinate : IEquatable<Coordinate>
{
     public Coordinate(int x, int y);
     public int X { get; }
     public int Y { get; }
     // override Equals and GetHashcode...
}

You can now create a collection of these Coordinate instances.

If you create a HashSet<Coordinate> you will be guaranteed that you cannot add a Coordinate if it's already added because it overrides Equals.

If you want, you can expand Coordinate to Coordinate<T> like this:

public class Coordinate<T> //...
{
    // previous stuff...

    public T Item { get; set; }
}

This will allow you to associate a strongly typed item with each coordinate, like this:

var items = new HashSet<Coordinate<string>>();
items.Add(new Coordinate<string>(1, 4) { Item = "Foo" });
items.Add(new Coordinate<string>(7, 19) { Item = "Foo" });
// ...
like image 195
Mark Seemann Avatar answered Sep 27 '22 16:09

Mark Seemann