cannot sort an array of char

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 11 05:20:53 PST 2014


On 11/11/14 6:07 AM, Ivan Kazmenko wrote:
> IK>> Why is "char []" so special that it can't be sorted?
>
> SS> Because sort works on ranges, and std.range has the view that
> SS> char[] is a range of dchar without random access. Nevermind
> SS> what the compiler thinks :)
> SS>
> SS> I believe you can get what you want with
> SS> std.string.representation:
> SS>
> SS> import std.string;
> SS>
> SS> sort(c.representation);
>
> Thank you for showing a library way to do that.
> I ended up with using a cast, like "sort (cast (ubyte []) c)".
> And this looks like a safe way to do the same.

It's safe but be careful. For instance, if c becomes an 
immutable(char)[] or const(char)[], then you will have undefined 
behavior. If you use the representation, it will properly reject this 
behavior.

> Now, std.utf's byCodeUnit and std.string's representation seem like
> duplicate functionality, albeit with different input and output types
> (and bugs :) ).

No, byCodeUnit is not an array, it's a range of char. They solve 
different problems, and mean different things.

Note, byCodeUnit should work for sort, I'm surprised it doesn't.

-Steve


More information about the Digitalmars-d-learn mailing list