How to sort a range
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Mar 9 22:22:39 PST 2016
On 03/09/2016 06:50 PM, rcorre wrote:
> sort calls to quicksort (for unstable, at least) which uses
> swapAt. swapAt takes the range by value, so it just swaps the values in
> its local copy.
Remembering that a range is not the collection, swapAt takes the range
by value but it does not copy the elements. So, sort() does sort the
original array:
import std.algorithm;
void main() {
auto a = [ 9, -1, 2, 0 ];
a.sort();
assert(a == [ -1, 0, 2, 9 ]);
}
> The original OnlyResult is untouched. I guess a static
> array slice maintains a pointer to the underlying array (which is why
> returning one from a function errors with 'escaping reference to local
> variable').
Yes: A static array is just a collection of elements, which implicitly
converts to a slice and a slice is nothing but a pair of "pointer to the
first element" and "number of elements".
Ali
More information about the Digitalmars-d-learn
mailing list