Iterators Must Go

Steven Schveighoffer schveiguy at yahoo.com
Fri May 8 19:34:52 PDT 2009


On Fri, 08 May 2009 11:57:41 -0400, Walter Bright  
<newshound1 at digitalmars.com> wrote:

> Steven Schveighoffer wrote:
>> You still have not addressed the usage of iterators as general data  
>> structure pointers.  As far as I can tell, ranges do not implement this.
>>  i.e. find surrounding elements of an element.
>>  With iterators:
>>  auto iter = container.find(elem);
>> auto elembefore = iter - 1;
>> auto elemafter = iter + 1;
>>  Assuming incrementing and decrementing an iterator is checked for  
>> out-of-bounds.
>
> The problem is that last statement - "Assuming". If the iterator is the  
> first or the last, or if there's only 1 or 2 elements in the container,  
> it's crash city. Iterators are *inherently* uncheckable.
>
> For finding the elemafter, it's trivial as find() returns a range from  
> the found element to the end (and it's also trivially checkable!).
>
> For elembefore, there's a bit more work involved, probably defining a  
> find() that returns a range backed up by one one.

You're assuming an iterator does not know its bounds.  Maybe I should call  
it something other than iterator.  How about cursor?

There are definite reasons to use containers in ways that don't involve  
std.algorithm, where something that has the easy ability to move back and  
forth N times without weird subrange operations.

I'm thinking of a structure with either a pointer to the container for  
bounds checking, or a range and pointer combined (where the invariant is  
that the pointer is always within the range).

I'm not saying ranges are not great, i think they are a HUGE step forward,  
but the statement "Iterators must be eliminated" may be too harsh.   
Perhaps the unchecked iterator, yes (but you may want to allow it in  
certain performance-critical code).

-Steve



More information about the Digitalmars-d mailing list