Associative array dup property?

dsimcha dsimcha at yahoo.com
Wed Jun 16 10:57:12 PDT 2010


== Quote from bearophile (bearophileHUGS at lycos.com)'s article
> Adrian Matoga:
> > So... is it a bug or is this feature missing intentionally?
> I have asked for a .dup for AAs something like three years ago, and probably
other people have asked for it years before. I think it will be added, but I
presume nobody has implemented it yet.
> > What would you recommend for concise, fast and safe surrogate?
> This is a possible version (untested):
> TV[TK] dup(TK, TV)(TV[TK] aa) {
>         TV[TK] result;
>         foreach (k, v; aa)
>             result[k] = v;
>         return result;
> }
> Bye,
> bearophile

Of course that works, but you can probably do it more efficiently if you work at a
lower level, inside aaA.d.  For example, in terms of unnecessary memory
allocations your function is roughly equivalent to using the following for
duplicating a regular array:

T[] dup(T)(T[] arr) {
    T[] ret;
    foreach(elem; arr) {
        ret ~= elem;
    }

    return ret;
}


More information about the Digitalmars-d mailing list