Static Initialization of Associative Arrays

badmadevil badmadevil at gmail.com
Mon Mar 31 06:31:00 PDT 2008


Jarrett Billingsley wrote:
> "Tyro[a.c.edwards]" <no at spam.com> wrote in message 
> news:fspu6h$2kps$1 at digitalmars.com...
>> D v2.012 currently allows the following:
>>
>> int[char[]] eroMatrix = ["SA":1, "SB":2, "SP":3, "KK":4];
>> foreach(k, v; eroMatrix)
>>  writefln(k, "->", v);
>>
>> // output:
>> SA->1
>> SB->2
>> SP->3
>> KK->4
>>
>> However attempts to directly access a "key:value" pair results in an 
>> ArrayBoundsError. Any idea why? Is there a temporary workaround available?
>>
>> writefln(eroMatrix["SA"]) // ArrayBoundsError
>>
>> Thanks,
>> Andrew
> 
> I would have expected something like:
> 
> writefln(eroMatrix[eroMatrix.keys[0]]);
> 
> to work, but it doesn't.
> 
> O_o 
> 

It seems matter only the _method_ of initialization.

int[char[]] eroMatrix = ["SA":1, "SB":2, "SP":3, "KK":4]; // literal

eroMatrix["00"]	= 9 ; // direct

foreach(k; eroMatrix.keys.sort) {
	writef(k, "->", typeid(typeof(k)), "->") ;
	writefln( eroMatrix[k]);
  }

 >>> OUTPUT:
00->const(char)[]->9
KK->const(char)[]->
Error: ArrayBoundsError aatst(10)

PS:D 2.0 change the key's type from char[] to const(char)[], D 1.0 not.

> 


More information about the Digitalmars-d-learn mailing list