网站建议:179001057@qq.com

Iterator(迭代器)模式

技术2022-05-11  1

作用:提供一种方法顺序访问一个聚合对象中各个元素,,而又不需暴露该对象的内部表示.

在STL的实现中,所有的迭代器(Iterator)都遵照了这套规范。另外在多种遍历方法中,如前序,后序,中序以及广度优先遍历等,都可以用不同的迭代器类来支持。

 

typedef int DATA;class Iterater;// 容器的抽象基类class Aggregate{public:virtual ~Aggregate(){}virtual Iterater* CreateIterater(Aggregate *pAggregate) = 0;virtual int GetSize() = 0;virtual DATA GetItem(int nIndex) = 0;};// 迭代器的抽象基类class Iterater{public:virtual ~Iterater(){}virtual void First() = 0;virtual void Next() = 0;virtual bool IsDone() = 0;virtual DATA CurrentItem() = 0;private:};

class ConcreateAggregate: public Aggregate{public:ConcreateAggregate(int nSize);virtual ~ConcreateAggregate();virtual Iterater* CreateIterater(Aggregate *pAggregate);virtual int GetSize();virtual DATA GetItem(int nIndex);private:int m_nSize;DATA *m_pData;};// 访问ConcreateAggregate容器类的迭代器类class ConcreateIterater: public Iterater{ public:ConcreateIterater(Aggregate* pAggregate);virtual ~ConcreateIterater(){}virtual void First();virtual void Next();virtual bool IsDone();virtual DATA CurrentItem();private:Aggregate *m_pConcreateAggregate;int m_nIndex;};

 

#include <iostream>#include "Iterator.h"ConcreateAggregate::ConcreateAggregate(int nSize): m_nSize(nSize), m_pData(NULL){m_pData = new DATA[m_nSize];for (int i = 0; i < nSize; ++i){m_pData[i] = i;}}ConcreateAggregate::~ConcreateAggregate(){delete [] m_pData;m_pData = NULL;}Iterater* ConcreateAggregate::CreateIterater(Aggregate *pAggregate){return new ConcreateIterater(this);}int ConcreateAggregate::GetSize(){return m_nSize;}DATA ConcreateAggregate::GetItem(int nIndex){if (nIndex < m_nSize){return m_pData[nIndex];}else{return -1;}}ConcreateIterater::ConcreateIterater(Aggregate* pAggregate): m_pConcreateAggregate(pAggregate), m_nIndex(0){}void ConcreateIterater::First(){m_nIndex = 0;}void ConcreateIterater::Next(){if (m_nIndex < m_pConcreateAggregate->GetSize()){ ++m_nIndex;}}bool ConcreateIterater::IsDone(){return m_nIndex == m_pConcreateAggregate->GetSize();}DATA ConcreateIterater::CurrentItem(){return m_pConcreateAggregate->GetItem(m_nIndex);}

 

int main(){Aggregate* pAggregate = new ConcreateAggregate(4);Iterater* pIterater = new ConcreateIterater(pAggregate);for (; false == pIterater->IsDone(); pIterater->Next()){std::cout << pIterater->CurrentItem() << std::endl;}return 0;}

 


最新回复(0)