AA's and mutating keys
Steven Schveighoffer
schveiguy at yahoo.com
Wed Oct 31 10:48:02 PDT 2007
It's ok if the AA makes a copy of the key, or uses something based on the
key (like a hashcode).
My code is less likely to be encountered in real life, but I have a more
probable example:
Let's say you were counting the number of occurrences of each word in a
file. You may do it by reading lines into a buffer. Then for each word in
the line, increment a counter in an AA that uses strings as the key and
integers as the value.
If you re-use the buffer, you might overwrite the key that you used to
insert an element into an AA! But it's not obvious to someone who normally
codes in C++ or Java, because strings are either pass by value or immutable.
I've used D for a few months now, and it isn't even obvious to me :)
I am running into this very situation, so I want to know whether an AA will
dup the key automatically or if I have to do it myself.
Plus, if I have to dup the key every time I just increment the count (not
the first insertion), that is a lot of wasted memory and copying. So I have
to do something like:
int *x = key in map;
if(x)
(*x)++;
else
map[key.dup] = 1;
which would be nice if it was done automatically for me :)
Also, if I do have to dup it myself, then the website should specify that
keys should not be modified once they are used to insert nodes into an AA.
-Steve
"Jarrett Billingsley" wrote
> "Steven Schveighoffer" <schveiguy at yahoo.com> wrote in message
> news:fga4ah$kov$1 at digitalmars.com...
>> There isn't any documentation that I can tell on the Arrays page that
>> determines whether a mutating key can be used for an AA. For example, if
>> I use char[] as a key:
>>
>> char[][char[]] map;
>>
>> char[] keyvalue = "hello";
>>
>> map[keyvalue] = "world";
>> keyvalue[] = "cello";
>>
>> char[] *val = "hello" in map;
>>
>> So does val get set to non-null?
>>
>> -Steve
>
> Never ever ever ever ever ever ever do this. Really. I'm pretty sure
> what you get from that 'in' is undefined.
>
> Some languages go so far as to disallow using mutable types as map keys
> (i.e. Python). It's just bad news.
>
More information about the Digitalmars-d-learn
mailing list