Top Up Prev Next Bottom Contents Index Search

1.2 Iterators

Iterators are a very basic and widely used concept in Ptolemy, and are used repeatedly in Ptolemy programming in almost any situation where a composite object contains other objects. We have chosen to use a consistent interface for all iterator objects. The typical iterator class has the following basic interface (some iterators provide additional functions as well):

class MyIterator {
// constructor: argument is associated outer object
// next: return a pointer to the next object,
// or a null pointer if no more
InnerObject* next();
// operator form: a synonym for next
InnerObject* operator++(POSTFIX_OP) {return next();}
// reset the iterator to point to the first object
void reset();
POSTFIX_OP is a macro that is defined to be an empty string on older compilers (such as cfront 2.1 and versions of g++ before 2.4) and to the string "int" with newer compilers. This conditional behavior is required because of the evolution of the C++ language; previously, postfix and prefix forms of the operators ++ and - were not distinguished when overloaded; now, a dummy int argument indicates that the postfix form is intended.

A typical programming application for iterators might be something like

// print the names of all objects in the container 
ListIter nextItem(myList);
Item *itemP;
while ((itemP = nextItem++) != 0) 
cout << itemP->name() << "\back n";
It is, as a rule, not safe to modify most container classes in parallel with the use of an iterator, as the iterator may attempt to access an object that does not exist any more. However, the reset member function will always make the iterator safe to use even if the list has been modified (user-written iterators should preserve this property).

Top Up Prev Next Bottom Contents Index Search
Copyright © 1990-1997, University of California. All rights reserved.