How to set array length for multidimensional static arrays

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 31 23:50:36 PST 2016


On Monday, 1 February 2016 at 07:42:56 UTC, Namal wrote:
> On Monday, 1 February 2016 at 07:41:33 UTC, Namal wrote:
>> I understand that I cannot pass a variable to the static array 
>> like in C++, and have to use dynamic arrays. But how can I set 
>> the length for them without using a loop?
>
> I mean std::vector in C++, not array.

I'm not sure I understand well because I know nothing about C++ 
types, so I'll assume you mean dynamic array.

Dynamic arrays are sized at initialization, resized when needed 
(when adding new elements) and can also be explicitely sized to 
some size:

     auto arr = [1, 2];

     arr ~= 3;
     assert(arr == [1, 2, 3]);
     assert(arr.length == 3);

     arr.length = 5;
     assert(arr == [1, 2, 3, 0, 0]);
     assert(arr.length == 5);

Note that new elements are set to the initial value of array 
elements (here int.init).

You can read more about this behaviour in the documentation: 
http://dlang.org/spec/arrays.html


More information about the Digitalmars-d-learn mailing list