D slicing

Andrej Mitrovic andrej.mitrovich at gmail.com
Mon Jun 17 16:44:29 PDT 2013


On Monday, 17 June 2013 at 23:34:46 UTC, Colin Grogan wrote:
> auto orig = [1,2,3,4,5,6,7];
> auto sliceEven = orig[0..$..2];
> auto sliceOdd = orig[1..$..2];
>

> But I dont think thats possible?

Not with arrays, they must be contiguous. But you can use ranges 
instead:

-----
import std.stdio;
import std.range;

void main()
{
     auto orig = [1,2,3,4,5,6,7];
     auto sliceEven = orig.stride(2);
     auto sliceOdd = orig.drop(1).stride(2);

     writeln(sliceEven);
     writeln(sliceOdd);
}
-----

You can convert the ranges into arrays by calling .array on them 
(and importing std.array first), but this will cause allocations.


More information about the Digitalmars-d-learn mailing list