foreach vs. iterators

Sean Kelly sean at f4.ca
Sat Nov 4 08:18:45 PST 2006


Georg Wrede wrote:
> 
> Back to foreach: it's syntactically a very convenient way to go through 
> a trivial collection (i.e. an array or a list). But for non-trivial 
> containers (or data structures), foreach simply is insufficient. You 
> need an iterator.

Assuming you simply want to visit every element once then I think 
foreach is fine.  In fact, it's generally simpler than implementing an 
iterator, given an arbitrary container type.  Where foreach falls down 
is if you want to stop after N iterations and resume later.  It's 
possible, but doing so resembles implementing random access iterators 
for a linked list.

 > Iterators were invented for the very purpose of
> walking through a black-box container, if you will. I'd almost say that 
> container-specific iterators are the only way to guarantee the lowest 
> complexity walk-through of an arbitrary black-box container.

I think iterators are intended to represent an arbitrary position in a 
sequence and present a means for visiting the remaining elements.  It's 
the "arbitrary position" part that foreach can't do.

> One could of course have foreach actually employ iterators. This gives 
> the ease of coding with foreach combined with the flexiblity, decoupling 
> and orthogonality offered by iterators.

Yup, and this is what C++ does with its for_each, transform, and other 
algorithms.

> But, as in the previous post, even this becomes cumbersome when we're 
> iterating over more than one container simultaneously, especially when 
> they're of different sizes or iterating in non-lockstep.

It's not terribly difficult--just a for loop with two or more iterators 
and conditions--but I would like to believe that this can be simplified.

> In general, the essence and elegance of the STL has not been too 
> prevalent in D libraries or algorithms. With the current expressive 
> power of D, one might expect to soon start seeing some of this.

I agree.  Currently, I've implemented basically all of the C++ algorithm 
library plus a few additional functions, but only for arrays.  Without 
iterators, I simply don't see the point in extending many of the 
algorithms to support other container types.  opIndex simply doesn't 
apply well to most other container types.


Sean



More information about the Digitalmars-d-announce mailing list