Initialize multi dimensional associative dynamic array

Ali Çehreli acehreli at yahoo.com
Sun Dec 2 11:27:23 PST 2012


On 12/02/2012 06:58 AM, js.mdnq wrote:
 >
 > How does one initialize an array defined as
 >
 > A[B][C] arr;
 >
 > dynamically? (A,B,C are types, for example, int[int][string])

Let me ask a related question: The following initialization does not 
work. Am I doing something wrong?

     int[int][string] arr = [ "hello" : [ 1 : 100, 2 : 200 ] ];

   Error: not an associative array initializer

 > I want to store an array, indexed by strings, of ints, indexed by ints.
 >
 > For example, What I want is a hash map that maps integers to integers so
 > I can do something like
 >
 > myval = arr[3243]; // has O(1) lookup
 >
 > But then I want to be able to extend this to use strings to subgroup the
 > arrays:
 >
 >
 > myval1 = arr["Group1"][3243]; // has O(1) lookup
 > myval2 = arr["Group2"][3243]; // has O(1) lookup
 >
 >
 > so my arr definition is
 >
 > int[int][string] arr;
 >
 > Or, another way to see it, is I want the Key's to be strings and the
 > values to be int[int].
 >
 > But when I try to access the value of the value I get an exception, I
 > believe, because I haven't initialized the value.

Allow me to repeat what bearophile said: It is very helpful if you show 
such problems in code. Even knowing the type of the exception is very 
helpful. Thanks.

 > (because if I do a
 > simple assign to the value it then works, but I'm trying to check if the
 > value exists in the first place)
 >
 > I've also tried playing around with something like int[string[int]] and
 > reversing the order(IIRC the order has to be backwards in the 
definition).

This works for me:

void main()
{
     int[int][string] arr;
     arr["hello"] = [ 1 : 100, 2 : 200 ];

     assert("world" !in arr);

     auto hello = "hello" in arr;

     // Note that 'in' produces a pointer:
     assert(typeid(hello) is typeid(int[int]*));
     assert(hello);
     assert(1 in *hello);
     assert(2 in *hello);
     assert(3 !in *hello);
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html



More information about the Digitalmars-d-learn mailing list