c++之迭代器模式
发布日期:2021-09-25 21:41:01 浏览次数:2 分类:技术文章

本文共 2371 字,大约阅读时间需要 7 分钟。

迭代器模式

定义:提供一种方法顺序访问一个集合对象中的元素,但是又不暴露该对象的内部显示

这里采用了类模板来定义类,强化对模板的运用。

代码:

#include 
#include
#include
using namespace std;//抽象迭代器类template
class Iterator{public: virtual T firstItem() = 0; virtual T nextItem() = 0; virtual T currentItem() = 0; virtual bool isEnd() = 0;};//抽象聚合类template
class Aggregate{public: virtual int count() = 0; virtual void pushItem(const T& str) = 0; virtual T removeItem(const int index) = 0; virtual Iterator
* createIterator() = 0;};//具体聚合类template
class ConcreteAggregate :Aggregate
{public: ConcreteAggregate() :m_pIter(nullptr){} ~ConcreteAggregate() { if (m_pIter) { delete m_pIter; m_pIter = nullptr; } } int count() { return m_listItem.size(); } void pushItem(const T& str) { m_listItem.push_back(str); } T removeItem(const int index) { T res; if (index < count()) { res = m_listItem[index]; } return res; } Iterator
* createIterator() { m_pIter = new ConcreteIterator
(this); return m_pIter; }private: vector
m_listItem; Iterator
*m_pIter;};//具体迭代器类template
class ConcreteIterator :public Iterator
{public: ConcreteIterator(Aggregate
* pA) :m_cnt(0), m_pConcreteA(nullptr) { m_pConcreteA = pA; } T firstItem() { return m_pConcreteA->removeItem(0); } T nextItem() { m_cnt++; if (m_cnt < m_pConcreteA->count()) { return m_pConcreteA->removeItem(m_cnt); } return T(); } T currentItem() { return m_pConcreteA->removeItem(m_cnt); } bool isEnd() { return ((m_cnt >= m_pConcreteA->count()) ? true : false); }private: Aggregate
*m_pConcreteA; int m_cnt;};//客户端int main(){ ConcreteAggregate
*p = new ConcreteAggregate < string > ; p->pushItem("宫保鸡丁"); p->pushItem("鱼香肉丝"); p->pushItem("翡翠白菜"); p->pushItem("青椒牛肉"); Iterator
*it = p->createIterator(); if (it) { string item = it->firstItem(); cout << "胖虎今天要吃的是菜是" << endl; while (!it->isEnd()) { cout << it->currentItem().c_str() << endl; it->nextItem(); } } cout << "====================" << endl; ConcreteAggregate
*p1 = new ConcreteAggregate
; p1->pushItem(999); p1->pushItem(888); p1->pushItem(666); p1->pushItem(555); Iterator
*pIter = p1->createIterator(); if (pIter) { int item = pIter->firstItem(); cout << "小明今天要学习的数字是" << endl; while (!pIter->isEnd()) { cout << pIter->currentItem() << endl; pIter->nextItem(); } } if (p) { delete p; p = nullptr; } if (p1) { delete p1; p1 = nullptr; } return 0;}

效果:

转载地址:https://blog.csdn.net/c_shell_python/article/details/107567398 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:c++之建造者模式
下一篇:c++深拷贝与浅拷贝

发表评论

最新留言

很好
[***.229.124.182]2024年04月23日 22时57分37秒