Remove all elements in an associative array

Nub Public nubpublic at gmail.com
Fri Jun 24 21:57:15 PDT 2011


On 6/25/2011 11:54 AM, Jonathan M Davis wrote:
> On 2011-06-24 20:41, Nub Public wrote:
>> Is there a way to remove all elements in an associative array?
>>
>> I tried clear() but it doesn't work. For some reason it sets the length
>> of the array to gibberish. What does clear() do exactly?
>
> clear invokes an object's destructor and puts it in an invalid state. You
> definitely don't want to do that to an associative array to empty it - if
> ever.
>
> Generally, the simplest thing to do to clear out an AA is to simply create a
> new one. Either set the existing one to null or assign it a new AA. The old
> one can then be garbage collected.

Thanks. That was very helpful.


> Now, if you actually need to remove all of
> the elements from the existing one (e.g. because multiple places in your code
> have references to it), then the only way that I'm aware of is to remove all
> of the elements one by one with remove.
>
> http://www.d-programming-language.org/hash-map.html
>
> - Jonathan M Davis

How to do this properly?

foreach (key, value; aa)
   remove(key);

This doesn't work since it's altering the aa in each iteration.


More information about the Digitalmars-d-learn mailing list