array idioms
Jonathan M Davis
jmdavisProg at gmx.com
Fri Feb 25 12:36:40 PST 2011
On Friday 25 February 2011 12:16:19 Steven Schveighoffer wrote:
> On Fri, 25 Feb 2011 15:09:44 -0500, Jonathan M Davis <jmdavisProg at gmx.com>
>
> 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.
Good to know. I was wondering. It's simple enough though to just make a list of
the keys to remove and then remove them afterwords.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list