Static arrays and std.algorithm.sort

John Colvin john.loughran.colvin at gmail.com
Fri Feb 21 04:56:45 PST 2014


On Thursday, 20 February 2014 at 17:24:55 UTC, D Apprentice wrote:
> Greetings, D wizards.
>
> Given a static array, int[5] a, presumed to be filled with 
> random
> numbers, how does one sort it using std.algorithm.sort? Calling
> sort(a) by itself errors out with:
>
> test.d(7): Error: template std.algorithm.sort does not match any
> function template declaration. Candidates are:
> /usr/share/dmd/src/phobos/std/algorithm.d(8387):
> std.algorithm.sort(alias less = "a < b", SwapStrategy ss =
> SwapStrategy.unstable, Range)(Range r) if ((ss ==
> SwapStrategy.unstable && (hasSwappableElements!Range ||
> hasAssignableElements!Range) || ss != SwapStrategy.unstable &&
> hasAssignableElements!Range) && isRandomAccessRange!Range &&
> hasSlicing!Range && hasLength!Range)
> test.d(7): Error: template std.algorithm.sort(alias less = "a <
> b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) if
> ((ss == SwapStrategy.unstable && (hasSwappableElements!Range ||
> hasAssignableElements!Range) || ss != SwapStrategy.unstable &&
> hasAssignableElements!Range) && isRandomAccessRange!Range &&
> hasSlicing!Range && hasLength!Range) cannot deduce template
> function from argument types !()(int[5])
>
> This is a general interest question. As I understand it, D 
> static
> arrays are value types, as opposed to their dynamic siblings
> which are reference types, and I suspect that is the underlying
> issue here.
>
> One little idiom I found, though I do not know if it's very
> efficient, is using the array slice syntax:
>
> sort (a[0..a.length]);
>
> This works, but I'm curious if there's another (better) way? The
> biggest advantage that I can see to the slice syntax is that it
> allows the programmer to sort only part of the array, which one
> could do in C with qsort.
>
> Source:
>
> import std.stdio;
> import std.algorithm;
>
> void main ()
> {
> 	int[5] a = [9, 5, 1, 7, 3];
> 	//sort (a); //Fails
> 	//sort (a[0..a.length]); //Works
> 	writeln (a);
> }
>
> Thank you for your time.

static arrays are not slices. Using [] gives you a slice from a 
static array. I often find myself writing this:

int[5] aStatic = [9, 5, 1, 7, 3];
auto a = aStatic[];

and just being careful not to leak references.


More information about the Digitalmars-d-learn mailing list