【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;
}
相关推荐
haibindev3 分钟前
在 Windows+WSL2 上部署 OpenClaw AI员工的实践与踩坑
linux·wsl2·openclaw
0xDevNull1 天前
Linux切换JDK版本详细教程
linux
进击的丸子1 天前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
Johny_Zhao3 天前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw
chlk1234 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑4 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件4 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
深紫色的三北六号5 天前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash5 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI5 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github