sort associative array by key

Timon Gehr timon.gehr at gmx.ch
Fri Nov 23 10:24:07 PST 2012


On 11/23/2012 07:09 PM, dsmith wrote:
> What is the best way to have a function sort an associative array by
> key?  The following yields a conversion error.
>
> double[string] aa_sort(double[string] aa) {
>    return aa.keys.sort;
> }
>
>

A hash table is unsorted by definition. What is it that you want to do 
exactly?

The following will generate a newly allocated dynamic array of key-value 
pairs, sorted by key:

import std.algorithm, std.typecons;

Tuple!(string, double)[] aa_sort(double[string] aa){
     typeof(return) r=[];
     foreach(k,v;aa) r~=tuple(k,v);
     sort!q{a[0]<b[0]}(r);
     return r;
}


More information about the Digitalmars-d-learn mailing list