2015-11-02 130 views
1

我正在構建數組的關聯數組。我嘗試使用appender,但獲得segfault。什麼是正確的方法來做到這一點?下面是小測試程序:Dlang數組關聯數組

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

我想,這可能與使用指針與附加目的地名單的事,但我不知道。有人知道什麼是錯的,並且是解決問題的好方法嗎?

回答

3

這裏該位是越野車無論:

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

如果新_IP爲空(這是每次在第一時間會發生什麼......)?當您試圖在下面解除引用時它仍然是空的!

嘗試將其更改爲這樣的事情:

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。

+0

謝謝,我現在只是完全避開了appender。 –