multiSort for sorting AA by value

Chris via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 21 05:05:37 PDT 2015


On Tuesday, 21 April 2015 at 11:46:24 UTC, bearophile wrote:
> Chris:
>
>> I'm happy with it, but maybe there is a more concise 
>> implementation?
>
> This is a bit shorter and a bit better (writefln is not yet 
> able to format tuples nicely):
>
>
> void main() {
>     import std.stdio: writeln;
>     import std.algorithm.sorting: multiSort;
>     import std.array: array;
>
>     const size_t[string] wCount = [
>         "hamster": 5,
>         "zorro": 80,
>         "troll": 90,
>         "algorithm": 80,
>         "beer": 80
>     ];
>
>     auto pairs = wCount.byKeyValue.array;
>     assert(wCount.length == pairs.length);
>     pairs.multiSort!(q{a.value > b.value}, q{a.key < b.key});
>     assert(pairs[2].key == "beer");
>     foreach (const ref it; pairs)
>         writeln(it.key, ": ", it.value);
> }
>
>
> Bye,
> bearophile

Nice!


More information about the Digitalmars-d-learn mailing list