Search code examples
algorithmsortingdassociative-array

sorting an associative array in D


This may not be the best idea, but i was trying to use some built in functionality of D to sort an associative array. so that i can do a slice of the top or bottom values for computations.

i have tried:

sort!((a,b) {return query[a] < query[b];})(query);

and:

sort(query);

resulting in the same error:

Error: template std.algorithm.sort cannot deduce function from argument types !()(int[string]), candidates are: /usr/local/Cellar/dmd/2.066.1/include/d2/std/algorithm.d(9384): std.algorithm.sort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) if ((ss == SwapStrategy.unstable && (hasSwappableElements!Range || hasAssignableElements!Range) || ss != SwapStrategy.unstable && hasAssignableElements!Range) && isRandomAccessRange!Range && hasSlicing!Range && hasLength!Range)

here is the entire class:

import std.stdio;
import std.array;
import std.algorithm;

import DataRow;
import LocationMap;

class Database{

this(){ /* intentionally left blank */}

public:
    void addRow(DataRow input){ this.db ~= input; }
    DataRow[] getDB(){ return this.db; }
    DataRow getDBRow(uint i){ return this.db[i]; }

    int[string] exportQuery(uint year){

        int[string] query;
        foreach (DataRow row ; db){
            if (row.getYear() == year){
                query[row.getCountryName()] = row.getExports;
            }
        }
        //sort!((a,b) {return query[a] < query[b];})(query);
        sort(query);
        return query;
    }

private:
    DataRow[] db;
    LocationMap locMap;
}

Solution

  • As Andrei said, you cant sort an associative array directly.

    You can, however, sort it's keys (or values for that matter) and access the array in a sorted fashion.

    int[string] myAA = ["c" : 3, "b" : 2, "a" : 1];
    foreach(key; myAA.keys.sort){ // myAA.values will access the values in the AA
        writefln("(Key, Value) = (%s, %s)", key, myAA[key]);
    }
    

    Will print

    (Key, Value) = (a, 1)
    (Key, Value) = (b, 2)
    (Key, Value) = (c, 3)
    

    This wouldnt be particularly efficient on a huge AA I dont think though.