Static arrays and std.algorithm.sort
Meta
jared771 at gmail.com
Thu Feb 20 09:43:44 PST 2014
I believe the problem is that std.algorithm.sort requires a
range, and fixed-size arrays are not ranges in D. I believe it's
because the most basic range functionality is the ability to do
this:
int[] arr = [0, 1, 2, 3];
while (arr.length > 0)
{
arr = arr[1..arr.length];
}
In other words, shrink the range size, which is obviously not
possible with a fixed-size array, since its size is... fixed. The
reason your example code works:
void main ()
{
int[5] a = [9, 5, 1, 7, 3];
//sort (a); //Fails
//Note that `a[0..a.length]` is equivalent to the shorter
syntax `a[]`
//sort (a[0..a.length]); //Works
writeln (a);
}
Is because while int[5] is not a range, int[] *is* a range, as I
demonstrated above. Although int[5] is not a range, you can
obtain a range "view" of it with the square brackets syntax. This
is referred to as slicing. The following are all valid slices of
an int[5]:
int[5] arr = [0, 1, 2, 3];
auto slice1 = arr[0..$]; //$ means arr.length in this context.
//slice1 == [0, 1, 2, 3]
auto slice2 = arr[1..$]; //slice2 == [1, 2, 3]
auto slice3 = arr[1..3]; //slice3 == [1, 2]
auto slice4 = arr[0..0]; //slice4 == [] empty slice, length == 0
but ptr != null
More information about the Digitalmars-d-learn
mailing list