Iterate over an array while mutating it?

Marc Schütz" <schuetzm at gmx.net> Marc Schütz" <schuetzm at gmx.net>
Fri Mar 28 03:58:22 PDT 2014


On Thursday, 27 March 2014 at 22:23:41 UTC, Anh Nhan wrote:
> Hey guys,
>
> I want to iterate over an array, while adding new entries, and 
> have those in the iteration loop.
>
> 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.
>
> Does somebody have a solution or approach for the loop to pick 
> up those new entries?

Reallocation will only happen if there isn't sufficient space 
left in the array. If you know the maximum number of elements in 
advance, you can reserve the necessary memory:

import std.array;
arr.reserve(arr.length + number_of_new_elements);


More information about the Digitalmars-d-learn mailing list