anonymous static array
Vijay Nayar
vnayar at wgen.net
Wed Mar 21 08:09:14 PDT 2012
Jesse's solution is correct, but I thought I'd throw in a
comment or two.
You are correct that the associative array is uninitialized
by default, and that you must initialize it. For very small
static arrays, a simple array literal like [1, 2, 3] would
suffice, but for larger arrays, this is a pain.
Here you can take advantage of the ".init" property that every
data-type has in D. For example, "float.init" is "NaN". Static
arrays are a unique type (the type includes the size), and it
has a ".init" property as well. Due to syntax constraints,
you must place the type in parenthesis to prevent the square
brackets from messing things up.
So instead of creating a temporary variable, you can do this:
void main() {
int[100][string] bob;
bob["happy"] = (int[100]).init;
bob["happy"][20] = 3;
assert(bob["happy"][20] == 3)
}
Have a good one,
- Vijay
On Wed, 21 Mar 2012, Jesse Phillips wrote:
> On Wednesday, 21 March 2012 at 10:51:05 UTC, Stephan wrote:
>> Hi,
>>
>> I have an associative array with strings as keys and static arrays as
>> values. When I access a new key, it gives me Range Error, so I think I
>> should initialise the associative array, but how?
>>
>> here is the code that fails:
>>
>> int[100][string] counts;
>> counts["some_key"][20]++;
>> // core.exception.RangeError at freqSpec(26): Range violation
>>
>>
>> Thanks,
>>
>> Stephan
>
> int[100][string] counts;
> int[100] a;
> counts["some_key"] = a;
> counts["some_key"][20]++;
>
>
More information about the Digitalmars-d-learn
mailing list