Foreach Access Violation

nobody somebody at somewhere.com
Tue Oct 21 01:04:25 PDT 2008


"bearophile" <bearophileHUGS at lycos.com> wrote in message 
news:gdj1gr$1dfn$1 at digitalmars.com...
> More comments added to the answers given by the other people.
>
> nobody:
>> Several apples are created:
>> Apple[] apples;
>> for(int i = 0; i < 10; i++)
>> {
>>     apples.length = apples.length + 1;
>>     apples[apples.length-1] = new Apple();
>> }
>
> If you know you want 10 apples then this is better (D2, but in D1 it's 
> similar):
>
> auto apples = new Apple[10];
> foreach (ref apple; apples)
>    apple = new Apple();
>
> If you don't know how many you will have:
>
> Apple[] apples;
> foreach (i; 0 .. find_number())
>    apples ~= new Apple();
>
> Finally if you don't know how many you will have, but you know they can be 
> a lot, then you can use an array appender, like the one discussed 
> recently.

I always forget append exists, thanks.

>
>
>> foreach(int i, Apple apple; apples)
>> {
>>      apples.iterate();
>> }
>
> Note this suffices here:
>
> foreach(apple; apples)
> {
>    apples.iterate();
> }

I know, but I was using the int i in my original code. Forgot to remove it 
in the example code I posted here :)

>
> Bye,
> bearophile 




More information about the Digitalmars-d-learn mailing list