Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Span and two dimensional Arrays

Is it possible to use the new System.Memory Span struct with two dimensional arrays of data?

double[,] testMulti = 
    {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 9.5f, 10, 11 },
        { 12, 13, 14.3f, 15 }
    };

double[] testArray = { 1, 2, 3, 4 };
string testString = "Hellow world";

testMulti.AsSpan(); // Compile error
testArray.AsSpan();
testString.AsSpan();

Whilst testArray and testString have a AsSpan extension, no such extension exists for testMulti.

Is the design of Span limited to working with single dimensional arrays of data?
I've not found an obvious way of working with the testMulti array using Span.

like image 785
Mick Avatar asked Oct 11 '18 00:10

Mick


People also ask

What is a 2 dimensional array?

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. For example, a nine-by-nine grid could be referenced with numbers for each row and letters for each column.

What are two-dimensional array explain with example?

Here i and j are the size of the two dimensions, i.e i denotes the number of rows while j denotes the number of columns. Example: int A[10][20]; Here we declare a two-dimensional array in C, named A which has 10 rows and 20 columns.

What is difference between dimensional array and two-dimensional array?

A one-dimensional array stores a single list of various elements having a similar data type. A two-dimensional array stores an array of various arrays, or a list of various lists, or an array of various one-dimensional arrays. It represents multiple data items in the form of a list.

Is multidimensional and two-dimensional array same?

Two – dimensional array is the simplest form of a multidimensional array. We can see a two – dimensional array as an array of one-dimensional array for easier understanding.


1 Answers

As John Wu already mentioned spans are one dimensional. You could of course implement a 2D span yourself, but Microsoft already did that for us.

Have a look into the docs here.
You can find the addressing nuget package here.
The package also provides a Memory2D.

 var arr = new int[,] { {1,2,3},{2,2,3},{3,2,3} };
 var spn = arr.AsSapn2D();
 // Now use it similar to a normal span
 // The access is of course a bit different since we are using a 2D data structure.
 Console.WriteLine(spn[0..2,..]);
like image 102
Alex Fischer Avatar answered Oct 26 '22 02:10

Alex Fischer