【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;
}
相关推荐
Johny_Zhao2 小时前
Keepalived与Nginx架构选型
linux·nginx·信息安全·云计算·apache·shell·yum源·keepalive·系统运维
FlightYe4 小时前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
by209995 小时前
Linux 文件描述符与重定向
linux·服务器
橙橙笔记6 小时前
Linux基础与命令的学习
linux·运维·服务器·shell
无奈笑天下6 小时前
银河麒麟桌面操作系统【命令行配置文件与图片搜索功能】操作方法
linux·运维·服务器
飞花漫卷,情随岁迁7 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
.道阻且长.8 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
学以智用9 小时前
CentOS 目录穿梭
linux
goehou10 小时前
改错一行 fstab,SSH 就再也连不上了
linux·运维·故障恢复·fstab
如夏倾城12 小时前
进程状态模型详解:从三态、五态到 Linux 状态码映射
java·linux·服务器