www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Why does sort not work on fixed arrays?

reply Brett <Brett gmail.com> writes:
T[N] t;
sort(t); fails

but

T[] t;
sort(t); passes


but magically

T[N] t;
sort(t[0..$]);  passes !!!
Sep 17 2019
next sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
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
Sep 17 2019
prev sibling next sibling parent Jonathan Marler <johnnymarler gmail.com> writes:
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.
Sep 17 2019
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
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
Sep 17 2019