Iterate over an array while mutating it?

Regan Heath regan at netmail.co.nz
Fri Mar 28 06:49:14 PDT 2014


On Thu, 27 Mar 2014 22:23:40 -0000, Anh Nhan <anhnhan at outlook.com> 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?

Wrap the array in an adapter class/struct which implements opApply for  
foreach...

import std.stdio;
import std.conv;

struct ForAdd(T)
{
   T[] data;

   this(T[] _data)  { data = _data; }

   void opOpAssign(string op : "~")(T rhs) { data ~= rhs; }

   int opApply(int delegate(ref T) dg)
   {
     int result = 0;

     for (int i = 0; i < data.length; i++)
     {
       result = dg(data[i]);
       if (result)
         break;
     }

     return result;
   }
}

int main(string[] args)
{
   string[] test;

   for(int i = 0; i < 5; i++)
     test ~= to!string(i);

   auto adder = ForAdd!string(test);
   foreach(string item; adder)
   {
     writefln("%s", item);
     if (item == "2")
       adder ~= "5";
     if (item == "4")
       adder ~= "6";
     if (item == "5")
       adder ~= "7";
   }

   return 0;
}

R

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list