【27】c++设计模式——>迭代器模式(1)

迭代器实现通常包含两个主要组件:迭代器和聚合对象,聚合对象一般是vector,list,set,map等,迭代器负责在聚合对象上进行遍历,并提供了一种统一的访问元素的方法。聚合对象用来存储,并提供创建迭代器的接口。通过将遍历算法与聚合对象分离开来。

迭代器接口

c 复制代码
#include <iostream>
#include <vector>

// 迭代器接口
class Iterator {
public:
    virtual bool hasNext() const = 0; //是否存在下一个元素
    virtual int next() = 0; //返回下一个元素
};

// 具体的迭代器实现
class ConcreteIterator : public Iterator {
private:
    std::vector<int> collection; //定义一个容器
    int position; 

public:
    ConcreteIterator(const std::vector<int>& coll) : collection(coll), position(0) {}

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

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

// 聚合对象
class Aggregate {
private:
    std::vector<int> collection;

public:
    void add(int item) {
        collection.push_back(item);
    }

    Iterator* createIterator() const {
        return new ConcreteIterator(collection);
    }
};

int main() {
    Aggregate aggregate;
    aggregate.add(1);
    aggregate.add(2);
    aggregate.add(3);

    Iterator* iterator = aggregate.createIterator();

    while (iterator->hasNext()) {
        int item = iterator->next();
        std::cout << item << " ";
    }

    delete iterator;

    return 0;
}
相关推荐
Linux-lucky1 小时前
21-Linux学习之旅之HTTPS和安全加固
linux·运维·学习·ubuntu·https
清水白石0082 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
ao-weilai3 小时前
Linux基础:Ext系列文件系统
linux·运维·服务器
qq_349447953 小时前
Linux系统,安装git,从使用git下载仓库(GitHub, Gitee, GitLab 等),并且使用ssh密钥,可以直接执行git pull
linux·git·ssh
mCell6 小时前
GitHub Actions 玩法大赏:一台远程主机的七种活法
linux·github·agent
盐焗鹌鹑蛋6 小时前
【Linux】动静态库的制作与使用
linux
艾伦_耶格宇7 小时前
【ELK】-4 logstash的搭建及操作
linux·运维·ubuntu·elk
mifengxing8 小时前
文件逻辑结构、物理结构与磁盘空闲存储空间管理
大数据·linux·运维·操作系统·计算机408
zhangrelay8 小时前
ROS 2 Lyrical 第9章 计算机视觉与摄像头应用
linux·笔记·学习·ubuntu·机器人·ros2