Why can't static arrays be sorted?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 4 19:19:13 PDT 2016


On Tuesday, October 04, 2016 20:05:15 TheGag96 via Digitalmars-d-learn wrote:
> I was writing some code today and ran into this oddity that I'd
> never come across before:
>
>      import std.algorithm : sort;
>      int[10] arr = [0, 3, 4, 6, 2, 1, 1, 4, 6, 9];
>      thing.sort();
>
> This doesn't compile. Obviously the .sort property works, but
> what about static arrays makes them unable to be sorted by
> std.algorithm.sort? Thanks.

The problem is that static arrays aren't ranges (calling popFront on them
can't work, because their length isn't mutable). However, you can slice a
static array to get a dynamic array which _is_ a range. e.g.

thing[].sort();

Just make sure that such a dynamic array does not outlive the static array,
or it will refer to invalid memory (which would not be a problem in this
case).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list