Dlang 数组的关联数组

Dlang associative array of arrays

我正在构建一个数组的关联数组。我尝试使用附加程序,但遇到了段错误。这样做的正确方法是什么?下面是小测试程序:

import std.stdio;
import std.array;

struct Entry {
    string ip;
    string service;
}


void main(string[] args) {
    Entry[3] ents;
    ents[0] = Entry("1.1.1.1", "host1");
    ents[1] = Entry("1.1.1.2", "host2");
    ents[2] = Entry("1.1.1.1", "dns");

    string[][string] ip_hosts;

    foreach (entry; ents) {
        string ip = entry.ip;
        string service = entry.service;

        string[] *new_ip = (ip in ip_hosts);
        if (new_ip !is null) {
            *new_ip = [];
        }
        auto app = appender(*new_ip);
        app.put(service);
        continue;
    }
    writeln("Out:", ip_hosts);
}

我认为这可能与在 appender 中使用指向列表的指针有关,但我不确定。有谁知道出了什么问题,以及解决问题的好方法吗?

无论如何,这里的一点是错误的:

    string[] *new_ip = (ip in ip_hosts);
    if (new_ip !is null) {
        *new_ip = [];
    }
    auto app = appender(*new_ip);

如果 new_ip 为 null(这是每次第一次发生的情况...)怎么办?当您尝试在下面取消引用它时,它仍然是 null!

试试把它改成这样:

    string[] *new_ip = (ip in ip_hosts);
    if (new_ip is null) { // check if it is null instead of if it isn't
        ip_hosts[ip] = []; // add it to the AA if it is null
        // (since it is null you can't just do *new_ip = [])
        new_ip = ip in ip_hosts; // get the pointer here for use below
    }
    *new_ip ~= service; // just do a plain append, no need for appender

每次循环都创建一个新的 appender 无论如何都是浪费时间,你不会从中得到任何东西,因为它不能重复使用它的状态两次。

但如果您确实想使用它:

    auto app = appender(*new_ip);
    app.put(service);
    *new_ip = app.data; // reassign the data back to the original thing

您需要将数据重新分配给 AA,以便保存。