Thread overview
Why does sort not work on fixed arrays?
Sep 17, 2019
Brett
Sep 17, 2019
Jonathan M Davis
Sep 17, 2019
Jonathan Marler
September 17, 2019
T[N] t;
sort(t); fails

but

T[] t;
sort(t); passes


but magically

T[N] t;
sort(t[0..$]);  passes !!!

September 17, 2019
On Tuesday, September 17, 2019 3:23:53 PM MDT Brett via Digitalmars-d wrote:
> T[N] t;
> sort(t); fails
>
> but
>
> T[] t;
> sort(t); passes
>
>
> but magically
>
> T[N] t;
> sort(t[0..$]);  passes !!!

sort operates on random-access ranges. Static arrays are not ranges. In order for them to be ranges, it would have to be possible to pop elements off of them, and that obviously won't work when the type has a fixed number of elements. Slicing a static array results in a dynamic array which is a slice of the static array, and that _is_ a random-access range, so it works with sort.

BTW, if you want to slice the entirety of a static array, you don't need indices. You can just do t[] rather than t[0..$].

- Jonathan M Davis



September 17, 2019
On Tuesday, 17 September 2019 at 21:23:53 UTC, Brett wrote:
> T[N] t;
> sort(t); fails
>
> but
>
> T[] t;
> sort(t); passes
>
>
> but magically
>
> T[N] t;
> sort(t[0..$]);  passes !!!

I believe T[N] t; sort(t); would pass t by value, so the sort function would actually do nothing to t, it would only operate on a copy of t that was passed on the stack.

September 17, 2019
On 9/17/19 5:23 PM, Brett wrote:
> T[N] t;
> sort(t); fails
> 
> but
> 
> T[] t;
> sort(t); passes
> 
> 
> but magically
> 
> T[N] t;
> sort(t[0..$]);  passes !!!
> 

std.algorithm.sort accepts a range. A fixed-sized array is not a range, since you can't pop the front part off and make it 1 smaller.

You can use sort(t[]) for the same effect.

-Steve