New linked list
Derek Parnell
derek at psych.ward
Thu May 11 17:11:14 PDT 2006
On Thu, 11 May 2006 09:52:10 -0700, Walter Bright wrote:
> Sean Kelly wrote:
>> Very cool. One thing... does this work:
>>
>> foreach( Person p; per.each )
>> {
>> if( p.age > 50 )
>> p.listRemove();
>> }
>>
>> ie. can you remove elements within a foreach?
>
> It's undefined behavior. foreach is entitled to assume that the
> aggregate is a loop invariant, although the contents of the aggregate's
> elements can change. This precludes things like resizing an array inside
> a foreach, etc.
This bit my bum yesterday too. I had code inside the foreach that added to
the list, only to discover that even though the elements were added, they
were ignored inside the same foreach loop.
--------- example.d -----------
import std.stdio;
import std.string;
void tester(char[] x)
{
writefln("Adding '%s'", x);
vList ~= x;
}
char[][] vList;
void main()
{
tester("abc");
tester("def");
tester("ghi");
version(FOR)
{ for(int i; i < vList.length; i++)
{
char[] p = vList[i];
writefln("Found '%s'", p);
if (std.string.find(p, "e") != -1)
{
tester("orang");
}
}
}
version(EACH)
{ foreach(char[] p; vList)
{
writefln("Found '%s'", p);
if (std.string.find(p, "e") != -1)
{
tester("orang");
}
}
}
}
---------- end of example.d ----------
c:\temp>build example -full -exec -version=FOR
Path and Version : y:\util\build.exe v2.10(1556)
built on Thu Apr 6 13:13:32 2006
Adding 'abc'
Adding 'def'
Adding 'ghi'
Found 'abc'
Found 'def'
Adding 'orang'
Found 'ghi'
Found 'orang'
c:\temp>build example -full -exec -version=EACH
Path and Version : y:\util\build.exe v2.10(1556)
built on Thu Apr 6 13:13:32 2006
Adding 'abc'
Adding 'def'
Adding 'ghi'
Found 'abc'
Found 'def'
Adding 'orang'
Found 'ghi'
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocracy!"
12/05/2006 10:08:16 AM
More information about the Digitalmars-d-announce
mailing list