allocating an array in an associative array

Steven Schveighoffer schveiguy at yahoo.com
Wed Feb 9 05:44:52 PST 2011


On Wed, 09 Feb 2011 07:58:12 -0500, Dominic Jones  
<dominic.jones at 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


More information about the Digitalmars-d-learn mailing list