Writing Iterators |
Writing iterators is fairly straightforward. You only need to implement all of the operations for the particular kind of iterator you wish to write. We use the continuing example of the stack template discussed earlier.
One proviso is that iterators generally need accent to the private variables in the class. Thus they are often defined with nested classes. Here is the declaration:
class Iterator : public std::iterator<std::forward_iterator_tag, T> {
This extra information with inheritance simply provides information to the compiler that informs it that it can be used with STL classes that need the features it provides.
The rest of the code can be found in ExpressionsIteratorCPP/stack.h.
Most operations are fairly standard. "++" is a bit unusual as an operator, so we take a moment to talk about it. "++" can be used both as a prefix and a postfix operator: ++it and it++. They have different semantics when used as part of an expression. ++it bumps up the iterator and returns the new value, while it++ returns the old value and then bumps up the iterator.
C++ arbitrarily decides that something written with signature
Iterator& operator++()
is the prefix form, while
Iterator& operator++()
represents the postfix form. Notice the difference in their definitions.
Note that one flaw in my iterator definition is that *it cannot be used on the left hand side of an assignment, because it is not returned by reference. To do this I would need to return a reference to the value field of the node. To get this to work I would need to change the definition of getValue() to return that reference.
Finally notice the definitions of methods begin() and end() of stack and how they use the Iterator definition.
Code using the iterator can be found in ExpressionsIteratorCPP/Expresssions.cpp.
Writing Iterators |