Here's bearophile's version of sorting an AA by value [1]

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);
}

Should we add it to the documentation of

1. http://dlang.org/phobos/std_algorithm_sorting.html#.multiSort
2. http://dlang.org/hash-map.html

I think it's quite a common task and people will duckduckgo or google for it.


[1] http://forum.dlang.org/thread/[email protected]#post-flvdtewuyehvdetoxjrw:40forum.dlang.org

Reply via email to