Clearing associative arrays

Oskar Linde oskar.lindeREM at OVEgmail.com
Tue Sep 18 00:31:17 PDT 2007


Martin Fuchs wrote:
> Is there a direct way to clear the content of associative arrays in one 
> step?
> I would expect a statement like "arr.clear();", "arr.erase();" or 
> "arr.removeall();" to do the work, but couldn't find one.
> Instead it seams I would have to use the following wordy an inefficient 
> approach:
> 
>         foreach(x; arr)
>             arr.remove(x); 

If you only want to clear the reference,

arr = null;

will do the trick. Otherwise, you need to resort to non-portable hackery 
(something like this should definitely be included in the compiler/runtime:)

private struct BB { void*[]b; size_t nodes; }

private union ToPtr(T) {T x; void * ptr; }

void clear(T,E)(T[E] aa) {
     ToPtr!(typeof(aa)) toptr;
     toptr.x = aa;
     BB* b = cast(BB*) toptr.ptr;
     if (b) {
         b.b = null;
         b.nodes = 0;
     }
}

use:

arr.clear();

Warning: hardly tested, but should work with DMD 1.020/Phobos.

Regards,

-- 
Oskar



More information about the Digitalmars-d mailing list