How to sort a range

rcorre via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 9 18:50:37 PST 2016


On Wednesday, 9 March 2016 at 16:53:08 UTC, Xinok wrote:
> On Wednesday, 9 March 2016 at 15:39:55 UTC, rcorre wrote:
>> Still curious as to why it fails; maybe the range is getting 
>> copied at some point? I guess I need to step through it.
>
> That's my suspicion as well. It seems that OnlyResult is 
> pass-by-value so every time it gets passed to another function, 
> it creates a copy of all the elements. A simple solution is to 
> provide a wrapper type which refers to the elements in the 
> original container.
>
> However, I'm going to argue that the sort function is fine but 
> the modifications you made to OnlyResult are incorrect. I tried 
> running your example of only(...).sort but got a compilation 
> error. Similarly, trying to sort a static array also gives a 
> compilation error. However, if I slice the static array before 
> passing it to sort (thus passing by reference), then it works 
> just fine.

Got it. 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. 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').

Meanwhile, I've realized my code probably doensn't need to remove 
duplicates anyways, so its a moot point, but still an interesting 
discovery :)


More information about the Digitalmars-d-learn mailing list