digitalmars.D - Why does sort not work on fixed arrays?
- Brett (8/8) Sep 17 2019 T[N] t;
- Jonathan M Davis (10/18) Sep 17 2019 sort operates on random-access ranges. Static arrays are not ranges. In
- Jonathan Marler (4/12) Sep 17 2019 I believe T[N] t; sort(t); would pass t by value, so the sort
- Steven Schveighoffer (5/19) Sep 17 2019 std.algorithm.sort accepts a range. A fixed-sized array is not a range,
T[N] t; sort(t); fails but T[] t; sort(t); passes but magically T[N] t; sort(t[0..$]); passes !!!
Sep 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
Sep 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.
Sep 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
Sep 17 2019