c++之迭代器模式

迭代器模式

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

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

代码:

#include <iostream>
#include <list>
#include <vector>

using namespace std;

//抽象迭代器类
template<typename T>
class Iterator
{
public:
	virtual T firstItem() = 0;
	virtual T nextItem() = 0;
	virtual T currentItem() = 0;
	virtual bool isEnd() = 0;
};

//抽象聚合类
template<typename T>
class Aggregate
{
public:
	virtual int count() = 0;
	virtual void pushItem(const T& str) = 0;
	virtual T removeItem(const int index) = 0;
	virtual Iterator<T>* createIterator() = 0;
};

//具体聚合类
template<typename T>
class ConcreteAggregate :Aggregate<T>
{
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<T>* createIterator()
	{
		m_pIter = new ConcreteIterator<T>(this);
		return m_pIter;
	}
private:
	vector<T> m_listItem;
	Iterator<T> *m_pIter;
};

//具体迭代器类
template<typename T>
class ConcreteIterator :public Iterator<T>
{
public:
	ConcreteIterator(Aggregate<T>* 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<T> *m_pConcreteA;
	int m_cnt;
};

//客户端
int main()
{
	ConcreteAggregate<string> *p = new ConcreteAggregate < string > ;
	p->pushItem("宫保鸡丁");
	p->pushItem("鱼香肉丝");
	p->pushItem("翡翠白菜");
	p->pushItem("青椒牛肉");
	Iterator<string> *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<int> *p1 = new ConcreteAggregate<int>;
	p1->pushItem(999);
	p1->pushItem(888);
	p1->pushItem(666);
	p1->pushItem(555);
	Iterator<int> *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;
}

效果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值