Iterate over an array while mutating it?

Infiltrator Lt.Infiltrator at gmail.com
Thu Mar 27 15:26:36 PDT 2014


On Thursday, 27 March 2014 at 22:23:41 UTC, Anh Nhan wrote:
> I want to iterate over an array, while adding new entries, and 
> have those in the iteration loop.

Depending on what you're trying to do, perhaps you would be 
better off just adding the entries all at once instead of 
iterating the array?


> See here: https://gist.github.com/AnhNhan/9820226
>
> The problem is that the foreach loop seemingly only iterates 
> over the original array, not minding the newly added entries.

That's correct.  foreach caches (which makes it faster) but means 
that you cannot mutate the range whilst iterating it.


> Does somebody have a solution or approach for the loop to pick 
> up those new entries?

Your best bet is probably a for loop:

for(int i = 0; i < arr.length; i++) { arr ~= element; ... }


More information about the Digitalmars-d-learn mailing list