Removing items from an Array

James Miller james at aatch.net
Mon Feb 20 19:45:45 PST 2012


On 18 February 2012 05:30, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> On Friday, February 17, 2012 14:44:42 Mars wrote:
>> On Friday, 17 February 2012 at 13:33:25 UTC, James Miller wrote:
>> > AAs don't keep the key order, so when you delete something out
>> > of it,
>> > what ever system iterates to the next pointer gets confused. Its
>> > generally a bad idea to modify an array as you loop through it.
>> >
>> > --
>> > James Miller
>>
>> Too bad. So, what would be the correct way to do this? I mean...
>> it's not that uncommon, to have this problem.
>> Are creating a new array while iterating over it, or creating a
>> list of elements to remove, and removing them afterwards, the
>> only ways to do this?
>
> That's the way that I'd do it.
>
> - Jonathan M Davis

Pretty much. To expand on Jonathan's answer, the problem with
iterating and deleting is that the conditions when the loop started
are not the same as the conditions at the middle or end. With a
fixed-size array, you can do it safely assuming you write the proper
conditions, and you don't accidentally convert it to a slice.
With removal, taking a small memory hit to create a new array tends to
be worth it, since you can reclaim the memory from the old one (which
is presumably bigger). This is the kind of condition that memory
"scratch" spaces are advocated for (often used in game dev, due to
massive data processing requirements at speed). However, I don't
suggest implementing said scratch space in D, since the GC pretty much
does this anyway.


More information about the Digitalmars-d-learn mailing list