C++中的迭代器模式

59 篇文章 0 订阅
52 篇文章 2 订阅

目录

迭代器模式(Iterator Pattern)

实际应用

自定义容器的迭代器

二叉树的迭代器

图的迭代器

总结


迭代器模式(Iterator Pattern)

迭代器模式是一种行为型设计模式,它提供了一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。迭代器模式使得不同的集合对象都可以使用相同的接口进行遍历,从而提高代码的可复用性和扩展性。

实际应用

自定义容器的迭代器

有一个自定义容器(`Container`)和它的迭代器(`Iterator`)且容器内包含整数元素,可以通过迭代器进行遍历。

#include <iostream>
#include <vector>

// 自定义容器
class Container {
public:
    void add(int value) {
        elements.push_back(value);
    }

    class Iterator {
    public:
        Iterator(std::vector<int>& elements, size_t position)
            : elements(elements), position(position) {}

        bool hasNext() const {
            return position < elements.size();
        }

        int next() {
            return elements[position++];
        }

    private:
        std::vector<int>& elements;
        size_t position;
    };

    Iterator getIterator() {
        return Iterator(elements, 0);
    }

private:
    std::vector<int> elements;
};

// 客户端代码:使用自定义容器和迭代器
int main() {
    Container container;
    container.add(1);
    container.add(2);
    container.add(3);

    Container::Iterator it = container.getIterator();
    while (it.hasNext()) {
        std::cout << it.next() << " ";
    }
    std::cout << std::endl;

    return 0;
}

二叉树的迭代器

支持中序遍历二叉树的迭代器。

#include <iostream>
#include <stack>
#include <memory>

// 二叉树节点
class TreeNode {
public:
    int value;
    std::shared_ptr<TreeNode> left;
    std::shared_ptr<TreeNode> right;

    TreeNode(int value) : value(value), left(nullptr), right(nullptr) {}
};

// 二叉树迭代器(中序遍历)
class BinaryTreeIterator {
public:
    BinaryTreeIterator(std::shared_ptr<TreeNode> root) {
        pushLeft(root);
    }

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

    int next() {
        auto node = stack.top();
        stack.pop();
        pushLeft(node->right);
        return node->value;
    }

private:
    std::stack<std::shared_ptr<TreeNode>> stack;

    void pushLeft(std::shared_ptr<TreeNode> node) {
        while (node) {
            stack.push(node);
            node = node->left;
        }
    }
};

// 客户端代码:使用二叉树迭代器进行中序遍历
int main() {
    auto root = std::make_shared<TreeNode>(1);
    root->left = std::make_shared<TreeNode>(2);
    root->right = std::make_shared<TreeNode>(3);
    root->left->left = std::make_shared<TreeNode>(4);
    root->left->right = std::make_shared<TreeNode>(5);

    BinaryTreeIterator it(root);
    while (it.hasNext()) {
        std::cout << it.next() << " ";
    }
    std::cout << std::endl;

    return 0;
}

图的迭代器

支持深度优先搜索(DFS)遍历的图(Graph)的迭代器,。

#include <iostream>
#include <vector>
#include <stack>
#include <unordered_map>
#include <memory>

// 图节点
class GraphNode {
public:
    int value;
    std::vector<std::shared_ptr<GraphNode>> neighbors;

    GraphNode(int value) : value(value) {}
};

// 图迭代器(深度优先搜索)
class GraphIterator {
public:
    GraphIterator(std::shared_ptr<GraphNode> startNode) {
        visited[startNode] = true;
        stack.push(startNode);
    }

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

    int next() {
        auto node = stack.top();
        stack.pop();
        for (const auto& neighbor : node->neighbors) {
            if (visited.find(neighbor) == visited.end()) {
                visited[neighbor] = true;
                stack.push(neighbor);
            }
        }
        return node->value;
    }

private:
    std::stack<std::shared_ptr<GraphNode>> stack;
    std::unordered_map<std::shared_ptr<GraphNode>, bool> visited;
};

// 客户端代码:使用图迭代器进行深度优先搜索遍历
int main() {
    auto node1 = std::make_shared<GraphNode>(1);
    auto node2 = std::make_shared<GraphNode>(2);
    auto node3 = std::make_shared<GraphNode>(3);
    auto node4 = std::make_shared<GraphNode>(4);
    auto node5 = std::make_shared<GraphNode>(5);

    node1->neighbors.push_back(node2);
    node1->neighbors.push_back(node3);
    node2->neighbors.push_back(node4);
    node3->neighbors.push_back(node5);

    GraphIterator it(node1);
    while (it.hasNext()) {
        std::cout << it.next() << " ";
    }
    std::cout << std::endl;

    return 0;
}

总结

迭代器模式通常可以帮助我们提供统一的方式遍历不同的集合,从而提高代码的可复用性和扩展性。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沉夢志昂丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值