On Fri, 25 Feb 2011 15:09:44 -0500, Jonathan M Davis <[email protected]> wrote:

On Friday, February 25, 2011 11:30:28 spir wrote:
Hello,

What's the idiomatic way to:

* delete an element in an associative array

If you have the key, then just use remove. The online documentation for
asseciative array discusses it. e.g.

b.remove("hello");

If you're looking to remove by value, however, you're going to have to figure out what its key is. And if you want to remove _all_ elements with the same value, then you're going to need to find _all_ of their keys. The best way to do that
would probably just be to use a foreach loop:

foreach(k, v; aa)
{
    if(v == value)
        aa.remove(k);
}

I'm not sure if there are any problems with removing from an associative array while iterating over it though. I wouldn't think so, but I don't know so. Worst case though, you save the list of keys to remove and then remove them all once
you have them all.

It is illegal to remove from an AA you are iterating. I've learned first hand that this causes subtle memory bugs. Do not do this.

However, dcollections supports this idiom via the purge operation:

foreach(ref doPurge, v; &mymap.purge)
   doPurge = (v == value);

-Steve

Reply via email to