Dynamic array handling

Adam D. Ruppe destructionator at gmail.com
Thu Nov 14 13:45:27 PST 2013


On Thursday, 14 November 2013 at 21:38:39 UTC, seany wrote:
> array_var = (1,2,3 ... etc)

In D, that'd look like:

auto array_var = [1,2,3,4,5....];

> array_var = array_var(1:2,4:$)

array_var = array_var[0 .. 1] ~ array_var[2 .. $];

array[x .. y] does a slice in D, with the first element of the 
array being element 0. The returned value is the array from x to 
y, not including y.

Then the ~ operator builds a new array out of the two pieces on 
either side. Note though: using ~ in a loop where you need high 
performance is generally a bad idea - it is convenient, but a 
little slow since it allocates space for a new array.

> a = somefunction_that_drops_the_4th_element(a); // a is reset,
>                                                 // and the

There's also a remove function in std.algorithm that can drop an 
item like this:

import std.algorithm;

array_var = array_var.remove(2); // removes the 3rd element 
(starting from 0, so index 2 is the third element)


This function btw performs better than the a[0 .. 1] ~ a[2 .. $] 
example above, since it modifies the array in place instead of 
building a new one.


More information about the Digitalmars-d-learn mailing list