BehavioralC++verifiedVerified

Iterator Pattern in C++

Provides a way to sequentially access elements of a collection without exposing its underlying representation.

How to Implement the Iterator Pattern in C++

1Step 1: Define a tree node structure

struct TreeNode {
    std::string value;
    std::vector<std::unique_ptr<TreeNode>> children;

    TreeNode(std::string v) : value(std::move(v)) {}
    void addChild(std::unique_ptr<TreeNode> child) {
        children.push_back(std::move(child));
    }
};

2Step 2: Depth-first iterator

class DFSIterator {
    std::vector<const TreeNode*> stack_;
public:
    explicit DFSIterator(const TreeNode* root) {
        if (root) stack_.push_back(root);
    }

    bool hasNext() const { return !stack_.empty(); }

    const TreeNode* next() {
        if (stack_.empty()) return nullptr;
        auto* node = stack_.back();
        stack_.pop_back();
        // Push children in reverse so leftmost is processed first
        for (auto it = node->children.rbegin(); it != node->children.rend(); ++it)
            stack_.push_back(it->get());
        return node;
    }
};

3Step 3: Iterate over the tree

int main() {
    auto root = std::make_unique<TreeNode>("A");
    auto b = std::make_unique<TreeNode>("B");
    b->addChild(std::make_unique<TreeNode>("D"));
    b->addChild(std::make_unique<TreeNode>("E"));
    root->addChild(std::move(b));
    root->addChild(std::make_unique<TreeNode>("C"));

    DFSIterator it(root.get());
    while (it.hasNext()) {
        std::cout << it.next()->value << " ";
    }
    std::cout << "\n"; // A B D E C
}

Iterator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Iterator Pattern in the Real World

Think of a TV remote control. Whether your playlist is on a Blu-ray disc, a streaming service, or a USB drive, you use the same next and previous buttons to cycle through content. The remote (iterator interface) abstracts away the completely different internal mechanisms each media source uses to retrieve the next item.