AA's and mutating keys
Jarrett Billingsley
kb3ctd2 at yahoo.com
Fri Nov 2 15:20:53 PDT 2007
"Steven Schveighoffer" <schveiguy at yahoo.com> wrote in message
news:fgctpf$1acr$1 at digitalmars.com...
>>> It's ok if the AA makes a copy of the key, or uses something based on
>>> the key (like a hashcode).
>
> You are half right :) The first part of my statement says "if the AA
> makes a copy of the key", so I think that is ok (and I think you agree).
I must have interpreted the 'or' in your first statement as 'xor' ;)
> <splitting hairs>
> In fact it is possible :)
>
> key[0] = 'h';
> map.remove(key);
> </splitting hairs>
PSSSSSHHHHH
> The performance hit of copying the string on first insertion is very
> minimal in most cases. I think the benefit far outweighs the cost. C++
> std::map does this, and nobody has ever complained about the performance
> hit.
>
> It would be nice to have a class/struct that wraps an AA with this
> behavior.
struct DupAA(V, K)
{
V[K] data;
static DupAA!(V, K) opCall(V[K] data)
{
DupAA!(V, K) ret;
ret.data = data;
return ret;
}
size_t length()
{
return data.length;
}
K[] keys()
{
return data.keys;
}
V[] values()
{
return data.values;
}
void rehash()
{
data.rehash;
}
V opIndex(K k)
{
return data[k];
}
void opIndexAssign(V v, K k)
{
if(auto val = k in data)
*val = v;
else
{
static if(is(typeof(k.dup)))
data[k.dup] = v;
else
data[k] = v;
}
}
int opApply(int delegate(inout V) dg)
{
foreach(v; data)
if(auto result = dg(v))
return result;
return 0;
}
int opApply(int delegate(inout K, inout V) dg)
{
foreach(k, v; data)
if(auto result = dg(k, v))
return result;
return 0;
}
}
void main()
{
DupAA!(int, char[]) map;
char[] key = new char[5];
key[] = "hello"[];
map[key] = 8;
key[0] = 'c';
map["cello"] = 2;
foreach(k, v; map)
Stdout.formatln("{}: {}", k, v);
}
WHAM BAM
More information about the Digitalmars-d-learn
mailing list