在D中对关联数组进行排序

Sti*_*ode 3 sorting algorithm associative-array d

这可能不是最好的主意,但是我试图使用D的某些内置功能对关联数组进行排序。这样我就可以对最高或最低值进行切片以进行计算。

我试过了:

sort!((a,b) {return query[a] < query[b];})(query);
Run Code Online (Sandbox Code Playgroud)

和:

sort(query);
Run Code Online (Sandbox Code Playgroud)

导致相同的错误:

错误:模板std.algorithm.sort无法从参数类型!()(int [string])推导函数,候选者为:/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)(范围r)if((ss == SwapStrategy.unstable &&(hasSwappableElements!Range || hasAssignableElements!Range )|| ss!= SwapStrategy.unstable && hasAssignableElements!Range)&& isRandomAccessRange!Range && hasSlicing!Range && hasLength!Range)

这是整个班级:

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;
}
Run Code Online (Sandbox Code Playgroud)

Col*_*gan 5

正如Andrei所说,您不能直接对关联数组进行排序。

但是,您可以对它的键(或相应的值)进行排序,并以排序的方式访问数组。

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]);
}
Run Code Online (Sandbox Code Playgroud)

将打印

(Key, Value) = (a, 1)
(Key, Value) = (b, 2)
(Key, Value) = (c, 3)
Run Code Online (Sandbox Code Playgroud)

不过,对于我不认为的大型机管局,这不会特别有效。