Iterators for D

Kristian Kilpi kjkilpi at gmail.com
Tue Nov 7 07:27:02 PST 2006


On Tue, 07 Nov 2006 16:03:13 +0200, Craig Black <cblack at ara.com> wrote:
> When writing custom C++ iterators, I find that end() is not ever  
> necessary.
> If end() is not used, it means that a little more smarts have to be  
> added to
> the iterator itself so that the iterator knows when to stop.  In some  
> cases
> this means that the iterator needs a pointer to the collection/container
> object in order to get that information.
>

A benefit of having a pointer to the iterated container is of course that  
boundary checks are always up to date, even if you change the container  
while iterating it. Well, I'm not saying that it would be the way to do  
the iterators, or that it's not the way to do them.

Btw, I have used (in C++) iterators having the following functions:

   isEnd()    //does the iterator point to the end position?  (isNotEnd()  
etc provided for convenience)
              //there is also: isBegin(), isFirst(), isLast()
   toBegin()  //to position -1 (which is outside the container)
   toFirst()  //to position 0
   toLast()   //to position end - 1
   toEnd()    //the end position points outside the container
   toNext()
   toPrev()
   get()      //returns the current item
   read()     //== get() + toNext()
   getNext()
   getPrev()
   readBackward()  //== get() + toPrev()
   ...

I have named iterators capable of changing the container as 'Writer's  
('wr' + 'iter'). They have the following functions:

   set()
   write()  //== set() + toNext()
   ...


Ok, there are a lot of functions... but my actual point is that the  
iterator has two positions, 'begin' and 'end', that point *outside* the  
container. When writing (or setting) a value to 'end', the value is  
appended to the end of the container (very natural operation for files).  
The same way "i.toBegin(); i.set(val);" inserts 'val' to the start of the  
container (very unnatural operation for files, and actually causes an  
error if tried for files).



More information about the Digitalmars-d mailing list