How to remove all items in an associative array?

Gregor Richards Richards at codu.org
Thu Oct 18 15:27:28 PDT 2007


Bill Baxter wrote:
> Oskar Linde wrote:
>> Bill Baxter wrote:
>>> Yang Bo wrote:
>>>> http://www.digitalmars.com/d/statement.html said:
>>>>
>>>> The aggregate must be loop invariant, meaning that elements to the
>>>> aggregate cannot be added or removed from it in the
>>>> NoScopeNonEmptyStatement.
>>>>
>>>> So, how can I remove them?
>>> I don't understand the body, but the answer to the question in the
>>> subject line is   AA = null;  or  AA = AA.init;
>> Since quite a while ago, the D associative arrays have become pure
>> reference types. While the above has the apparent effect of clearing the
>> array, it does in fact just reassign the current reference. If you have
>> several references to the same associative array, the above will not
>> clear the actual array referred to.
>>
>> To clear the actual array, you need to resort to 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;
>>     }
>> }
>>
>>> http://www.prowiki.org/wiki4d/wiki.cgi?DocComments/Arrays
>> I rewrote that section in a way that hopefully explains the semantics
>> better.
>>
>> This question comes up frequently enough to merit an addition to the
>> official documentation and a clear/deleteAll implementation (like the
>> one above) should definitely be added to the language and
>> phobos/internal/aaA.d.
> 
> Interesting tidbit.  Thanks for the info and for updating that page.
> 
> --bb

Unless the performance is a huge hit, it would probably be wiser to use
code that isn't dependent on the current implementation of AAs:

foreach (k; aa.keys.dup) {
    aa.remove(k);
}

I think that's in O(nlogn). The other code is free, but
implementation-specific. Ideally there would just be a .clear property :)

 - Gregor Richards



More information about the Digitalmars-d mailing list