1

私はD2プログラミング言語にかなり慣れていません。クワッド エッジ データ構造を実装する必要があります。これは、効果的なグラフ埋め込みとその双対のための隣接データ構造です。以前の C の経験から、次の実装から始めました。

struct edge(T) {
    edge* next;
    T* data;
    uint position;
}
alias edge[4] qedge;
edge* new_edge() {
    qedge* q = new qedge; // does not compile, just analogous
    // initialize the four edges (q[i].position = i)
    return cast (edge*) q;
}

それはうまくいきますが、この位置フィールドは私を悩ませています - それはそこにあるスペースを無駄にしているだけです. qedge 配列にメモリを割り当てるときに (8 * ${machine word size}) 境界に合わせる方法はありますか (その場合、追加の位置フィールドは必要ありません。配列はエッジ アドレスにエンコードされます)?

私は効率的でかわいい実装を目指しているので (それが私が D を選んだ理由です)、他の提案は大歓迎です。

編集:これは、物事をより明確にするためのコードですhttp://dpaste.dzfl.pl/e26baaad :

module qedge;

class edge(T) {
    edge next;
    T* data;
}

alias edge!int iedge;
alias iedge[4] qedge;

import std.stdio;
import std.c.stdlib;

void main() {
    writeln(iedge.sizeof); // 8
    writeln(qedge.sizeof); // 32
    // need something for the next line, 
    // which always returns an address, divisible by 32
    qedge* q = cast (qedge*) malloc(qedge.sizeof);
    writeln(q); // ex. 0x10429A0 = 17050016, which is, does not start at 32-byte boundary
}
4

1 に答える 1

1

質問に直接答えるには、を使用しalign(N)て必要な配置を指定します。ただし、これを覚えておいてください(dlang.orgからの引用):Do not align references or pointers that were allocated using NewExpression on boundaries that are not a multiple of size_t

http://dlang.orgのリファレンスマニュアルには、アライメントに関するセクションがあります-http://dlang.org/attribute.html#align

たとえば、Tはintです。64ビットアーキテクチャでは、edge!intはすでに24バイトの大きさです。DはCと整列においてそれほど違いはありません。以下を確認してください(実行可能/編集可能なコード:http://dpaste.dzfl.pl/de0121e1):

module so_0001;
// http://stackoverflow.com/questions/11383240/custom-alignment-options-for-an-efficient-quad-edge-implementation

struct edge(T) {
    edge* next;
    T* data;
    uint position;
}
alias edge!int iedge;
alias edge!int[4] qedge;

/* not a good idea for struct... it is a value type...
edge!int new_edge() {
    // in the original example it used new... D is not C++ to mix value and reference types! :)
}
*/

import std.stdio;

int main() {
    writeln(iedge.sizeof);

    //                                   64bit
    //                                ----------
    writeln(iedge.next.offsetof);     // 0
    writeln(iedge.data.offsetof);     // 8
    writeln(iedge.position.offsetof); // 16
    writeln(qedge.sizeof);
    return 0;
}
于 2012-07-08T13:48:41.017 に答える