www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Dinamyc arrays

reply Timofey <tipo3ro gmail.com> writes:
I`ve just started learning d and have a question.
What should I write to set dinamyc rectangular array length in 
both dimentions?
For example, I have declareted an array:
```   int[][] matrix;```
and want set it as n*n matrix.
Thanks
Sep 17 2023
next sibling parent Salih Dincer <salihdb hotmail.com> writes:
On Sunday, 17 September 2023 at 17:15:34 UTC, Timofey wrote:
 I`ve just started learning d and have a question.
 What should I write to set dinamyc rectangular array length in 
 both dimentions?
 For example, I have declareted an array:
 ```   int[][] matrix;```
 and want set it as n*n matrix.
 Thanks
There are many ways to do this, but I can quickly show you two: ```d import std.stdio; void main() { int[][] matrix;    enum n = 6; // method 1:    //matrix = new int[][](n, n); /* // method 2:    matrix.length = n;    foreach(ref e; matrix)        e.length = n;//*/     matrix.writeln; } ``` SDB 79
Sep 17 2023
prev sibling parent user1234 <user1234 12.de> writes:
On Sunday, 17 September 2023 at 17:15:34 UTC, Timofey wrote:
 I`ve just started learning d and have a question.
 What should I write to set dinamyc rectangular array length in 
 both dimentions?
 For example, I have declareted an array:

 ```d
 int[][] matrix;
 ```

 and want set it as n*n matrix.
 Thanks
You can flatten the mat and use operator overloads. Here's a some basic code to get started: ```d struct SquaredMat(T) { size_t dim; T[] array; this(usize dim) { this.dim = dim; array.length = dim * dim; } auto opIndex(size_t x, size_t y) { return array[x * dim + y]; } auto opIndexAssign(size_t x, size_t y, T value) { array[x * dim + y] = value; return this; } } ``` Those kind of type should already exist in 3rd part native D libraries, e.g "MIR" has something called "NDSlice" IIRC.
Sep 17 2023