Assigning to slice of array
Steven Schveighoffer
schveiguy at yahoo.com
Thu Mar 1 21:31:49 UTC 2018
On 3/1/18 4:16 PM, Jamie wrote:
> I'm trying to understand arrays and have read a lot of the information
> about them on this forum. I think I understand that they are set-up like
> Type[], so that int[][] actually means an array of int[].
>
> I create an array as per the following:
> auto arr = new int[3][2][1];
> which produces:
> [[0, 0, 0], [0, 0, 0]]
No, I think you did int[3][2], if you got that output. Otherwise it
would have been:
[[[0,0,0],[0,0,0]]]
Looking at the rest of your code, I think it wouldn't work if you had
done the line above.
> (for each of the following assignments, assume that the array is set
> back to zeros)
>
> and I can change the 2nd element of the 1st array using:
> arr[0][1] = 4;
> which produces:
> [[0, 4, 0], [0, 0, 0]]
>
> and I can change the entire 1st array using:
> arr[0][0 .. 3] = 5;
> which produces:
> [[5, 5, 5], [0, 0, 0,]]
Yes, all correct.
>
> however when I try and change elements across arrays rather than within
> arrays my understanding breaks down..
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
> 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].
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
More information about the Digitalmars-d-learn
mailing list