【问题标题】:sorting an associative array in D在 D 中对关联数组进行排序
【发布时间】:2015-06-11 09:24:32
【问题描述】:

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

我试过了:

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

和:

sort(query);

导致同样的错误:

错误:模板 std.algorithm.sort 无法从参数类型推导出函数!()(int[string]),候选者是: /usr/local/Cellar/dmd/2.066.1/include/d2/std/algorithm.d(9384): std.algorithm.sort(别名少 = "a

这是整个班级:

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

【问题讨论】:

    标签: algorithm sorting d associative-array


    【解决方案1】:

    关联数组不能排序——它们有自己的固有结构,不允许移动东西。这是哈希表课程的标准。

    要对任何内容进行排序,您必须首先将其放入随机访问结构中,很可能是数组。

    【讨论】:

      【解决方案2】:

      正如 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]);
      }
      

      将打印

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

      这在我不认为的巨大 AA 上不会特别有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 2011-12-20
        • 2016-02-01
        • 1970-01-01
        • 2018-04-01
        相关资源
        最近更新 更多