How to remove all items in an associative array?

Oskar Linde oskar.lindeREM at OVEgmail.com
Thu Oct 18 01:44:19 PDT 2007


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.

-- 
Oskar



More information about the Digitalmars-d mailing list