Assigning to slice of array

Jamie jamieborder01 at gmail.com
Thu Mar 1 22:43:52 UTC 2018


On Thursday, 1 March 2018 at 21:31:49 UTC, Steven Schveighoffer 
wrote:
> No, I think you did int[3][2], if you got that output. 
> Otherwise it would have been:
>
> [[[0,0,0],[0,0,0]]]

Yes apologies that was there from a previous attempt, you are 
correct.

> Well, that's because that type of slicing isn't supported 
> directly. You can't slice an array cross-wise like that.
>
> You may be interested in ndslice inside mir: 
> http://docs.algorithm.dlang.io/latest/mir_ndslice.html

Thanks I've just had a quick read and this looks promising for 
what I want (similar functionality to numpy), but I also want to 
understand arrays.

>> when I try
>>      arr[0 .. 2][0] = 3;   // which I think is equivalent to 
>> arr[0][0]
>
> Consider the array:
>
> int[] x = new int[2];
>
> Now, what would the slice x[0 .. 2] be? That's right, the same 
> as x.
>
> So when you slice arr[0 .. 2], it's basically the same as arr 
> (as arr has 2 elements).
>
> So arr[0 .. 2][0] is equivalent to arr[0].

So if I do
     arr[0 .. 1][0] = 3;
shouldn't this return
     [[3, 0, 0], [0, 0, 0]] ? Because I'm taking the slice arr[0 
.. 1], or arr[0], which is the first [0, 0, 0]? Then assigning 
the first element to 3?
instead it returns
     [[3, 3, 3], [0, 0, 0]]

> One thing that is interesting is that you assigned 3 to an 
> array, and it wrote it to all the elements. I did not know you 
> could do that with static arrays without doing a proper slice 
> assign. But it does compile (I learn something new every day).
>
> -Steve
Well I'm learning a lot today :)




More information about the Digitalmars-d-learn mailing list