foreach vs. iterators

Bill Baxter wbaxter at gmail.com
Sun Nov 5 10:08:34 PST 2006


Bill Baxter wrote:
> Sean Kelly wrote:
> 
>> Sean Kelly wrote:
>>
>>> Still, I think it's useful to have in an iterator, so perhaps 
>>> something roughly like this:
>>>
>>> interface Iterator(T)
>>> {
>>>     T val();
>>>     T next();
>>>     bool hasNext();
>>> }
>>
>>
>>
>> Err... this doesn't work for an iterator returned for an empty 
>> container.  
> 
> 
> It's fine if you define the behavior to be that you have to call next() 
> once to get the first value.  So for iteration idiom becomes:
> 
> T v;
> while(c.hasNext()) )
> {
> }

...another victem of Ctrl+Enter....

while(c.hasNext())
{
    T v = c.next();
}

I think an alias for T also needs to be a part of the definition of the 
iterator.  Like  alias T value_type.

Also would do you do a mutating iteration over collections of basic 
value types (eg floats), structs, and classes?  I.e. if you want to do 
something like:

while(c.hasNext())
{
    T v = c.next();
    v += 2;
}
where T could be float, struct, or class.  Ok, class case is fine, but 
the other two aren't clear to me.  Mutable iterator over structs could 
maybe return a pointer to each struct.  Basic value type, I'm not sure. 
  Just woke up though... maybe it's obvious and my head just isn't 
working yet.

--bb



More information about the Digitalmars-d-announce mailing list