Why std.algorithm.sort can't be applied to char[]?
Charles Hixson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 12 11:08:47 PDT 2014
On 05/12/2014 09:29 AM, Jonathan M Davis via Digitalmars-d-learn wrote:
> On Mon, 12 May 2014 14:49:52 +0000
> hane via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
>
>> and is there any way to sort char array with algorithm.sort?
>> ---
>> import std.algorithm;
>> import std.range;
>>
>> void main()
>> {
>> int[] arr = [5, 3, 7];
>> sort(arr); // OK
>>
>> char[] arr2 = ['z', 'g', 'c'];
>> sort(arr2); // error
>> sort!q{ a[0] > b[0] }(zip(arr, arr2)); // error
>> }
>> ---
>> I don't know what's difference between int[] and char[] in D, but
>> it's very unnatural.
> All strings in D are treated as ranges of dchar, not their element type. This
> has to with the fact that a char or wchar are only part of a character. If you
> want to sort arrays of characters, you need to use dchar[].
>
> http://stackoverflow.com/questions/12288465
> http://stackoverflow.com/questions/16590650
>
> - Jonathan M Davis
>
Given that he was working with pure ASCII, he should be able to cast the
array to byte[] and sort it, but I haven't tried. Also char[] isn't
string. Strings are immutable, and thus cannot be sorted in place. To
me this looks like an error in sort that he should be able to work
around with a cast.
--
Charles Hixson
More information about the Digitalmars-d-learn
mailing list