Step 2 of 5
Writing an iterator class
When the data isn't contiguous (a linked list, a tree, a file), you write an iterator class. For a forward iterator you need:
operator*to get the current elementoperator++(prefix) to advance, returning*thisoperator==to compare (C++20 generates!=for you)
class Iter {
public:
explicit Iter(Node* n) : node_(n) {}
int& operator*() const { return node_->value; }
Iter& operator++() { node_ = node_->next; return *this; }
bool operator==(const Iter& o) const { return node_ == o.node_; }
private:
Node* node_;
};
end() is simply an iterator holding nullptr, the position one past the last node.
Your turn: finish the Iterator inside IntList and add begin() and end().
Previous: Making a class iterable Next: Iterator concepts and algorithms