www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - allocating an array in an associative array

reply Dominic Jones <dominic.jones qmul.ac.uk> writes:
Hello,
I want to allocate the "int[]" array for a particular key in

  int[][string] list;

by doing

  list[key].length = list[key].length + 1;

but it does not work. I get an array bounds error. I am using gdc 4.3.5. Any
suggestions?

Thank you,
Dominic Jones
Feb 09 2011
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Wed, 09 Feb 2011 07:58:12 -0500, Dominic Jones  
<dominic.jones qmul.ac.uk> wrote:

 Hello,
 I want to allocate the "int[]" array for a particular key in

   int[][string] list;

 by doing

   list[key].length = list[key].length + 1;

 but it does not work. I get an array bounds error. I am using gdc 4.3.5.  
 Any
 suggestions?

Try using the in operator: if(auto arr = key in list) // arr is now type int[]* { (*arr).length = (*arr).length + 1; } else list[key] = new int[1]; // or larger if desired It incurs a double lookup when the key doesn't exist yet, but I'm not sure you can do any better (unless you know ahead of time the key is not in the AA). The issue is you are looking up list[key] without it existing, that throws the array bounds. The in check in my code checks to see if it is present first before doing anything. If they key is present, then there's only a single lookup. -Steve
Feb 09 2011