foreach vs. iterators
Sean Kelly
sean at f4.ca
Thu Nov 2 21:50:16 PST 2006
Walter Bright wrote:
> Sean Kelly wrote:
>> Forgive me for resurrecting a horribly battered equine, but I was
>> thinking about this a bit tonight and I've decided that foreach,
>> foreach_reverse, and array operations are not a sufficient general
>> substitute for C++ iterators.
>>
>> For example, let's say I want to compute the set union of two sorted
>> ranges, one of size M, the other of size N. By iterating across the
>> two ranges simultaneously is is easy to see that the complexity for
>> the operation will be max(M,N). In C++ this is easily accomplished
>> using forward iterators, and the ranges can be anything from arrays to
>> SQL result sets.
>>
>> In D however, there is no way to iterate across multiple ranges
>> simultaneously using foreach, so opIndex must be used instead. With
>> containers that have a constant-time lookup cost this isn't a big
>> deal, but what if these containers are binary trees? The complexity
>> for such an operation would be M(log(M)) + N(log(N)).
>>
>> 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.
>
> You are correct in regards to looping across multiple aggregates
> simultaneously.
>
> On the other hand, C++ iterators aren't a general substitute for
> opApply. For example, it is not at all easy to turn a recursive data
> structure (i.e. binary tree) into a linearized iterator.
Agreed. I think both approaches have merit. I suppose I was merely
hoping that foreach would work for everything.
Sean
More information about the Digitalmars-d-announce
mailing list