foreach vs. iterators

Bill Baxter wbaxter at gmail.com
Fri Nov 3 18:58:46 PST 2006


Oskar Linde wrote:
> Sean Kelly wrote:
> 
>>  From this it seems clear that foreach is not sufficiently adaptable 
>> to meet the needs of all sequential algorithms and opIndex is not a 
>> reasonable substitute for all cases where foreach may not be used.  
>> What alternatives do we have?  So far, iterator variants are all I've 
>> been able to come up with.
> 
> 
> I agree, and I have been saying this countless times. :)
> 
> Why don't we come up with a standard iterator concept for D?
> For a forward iterator, C++ has:
> 
> *i
> i++ / ++i
> i != end

One big concern I have with the current iterators is that the approach 
supported for the general case is deemed too inefficient for built-in 
arrays.  So arrays are special-cased by the compiler in the foreach 
logic to become more like a simple for loop.  But I want that speed for 
foreach-ing my own classes too!  Why should I be satisfied with less 
that peak performance for *my* classes if it's not considered good 
enough for built-in classes?

I have to pay this penalty even if my class is a simple wrapper around 
an array, that say does nothing more than add an opAdd so I can add two 
arrays together.


Plain old C++-style iterators don't have that problem.  For simple cases 
iter++  bascially compiles down to be equivalent to pointer manipulation.

--bb



More information about the Digitalmars-d-announce mailing list