Why std.algorithm.sort can't be applied to char[]?

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 12 07:56:45 PDT 2014


On Monday, 12 May 2014 at 14:49:53 UTC, hane 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.

char[] is a rather special type of array: the language has 
unicode support and iterates over it by code-point (i.e. not 
guaranteed to be a single char per iteration).

If you want to sort chars and are assuming ASCII, you can just 
use std.string.representation to work with them as integer types:

import std.algorithm;
import std.range;
import std.string;

void main()
{
   int[] arr = [5, 3, 7];
   sort(arr); // OK

   char[] arr2 = ['z', 'g', 'c'];
   sort(arr2.representation); // error
   sort!q{ a[0] > b[0] }(zip(arr, arr2.representation)); // error
}


More information about the Digitalmars-d-learn mailing list