Iterate over an array while mutating it?
Anh Nhan
anhnhan at outlook.com
Thu Mar 27 15:47:40 PDT 2014
On Thursday, 27 March 2014 at 22:26:37 UTC, Infiltrator wrote:
> 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; ... }
On Thursday, 27 March 2014 at 22:27:18 UTC, bearophile wrote:
> Anh Nhan:
>
>> I want to iterate over an array, while adding new entries, and
>> have those in the iteration loop.
>
> Don't iterate an array with foreach while you mutate it, even
> if you manage to make it work, the code is not clear.
> I suggest to use a C-style for loop with an index and specify
> in the code exactly what you want to do with the array and the
> index. The resulting code is clear and safe.
>
> Bye,
> bearophile
Ah, that the foreach caches the entries would make sense. I tried
creating iterators Java-style, which did not pick up the new
entries, too.
It works with for-loops. Thanks for the explanations, they helped
a lot.
Anh Nhan
More information about the Digitalmars-d-learn
mailing list