繁体   English   中英

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

我认为这可能与使用带有附加程序的列表的指针有关,但是我不确定。 有谁知道这是怎么回事,并且是解决此问题的好方法?

不管是否:

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

如果new_ip为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,以便将其保存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM