Iterator模式(C++迭代器模式),iterator模式

來源:互聯網
上載者:User

Iterator模式(C++迭代器模式),iterator模式

基本上來說,Iterator模式並沒有什麼可多說得,在STL中見得實在太多了,一般用於遍曆資料結構,其實現也相對簡單。

 

 代碼如下:

//////////////////////////////////////////////////////////////////////////// author: Jeson Yang//date:2014.12.10//file:main.cpp//////////////////////////////////////////////////////////////////////////#include <iostream>using namespace std;class Interator;class Aggregate{public:virtual ~Aggregate(){}virtual Interator* CreateItrator()=0{};virtual int GetSize()=0{}virtual int GetItem(int index)=0{}protected:Aggregate(){}};class ConcreteAggregate:public Aggregate{public:enum{size=3};ConcreteAggregate(){for(int i=0;i < size;i++)m_obj[i]=i;}~ConcreteAggregate(){}Interator* CreateItrator();int GetItem(int index){if(GetSize()) return m_obj[index];else return -1;}int GetSize(){return size;}private:int m_obj[size];};class Interator{public:virtual ~Interator(){};virtual void First()=0;virtual void Next()=0;virtual bool IsDone()=0;virtual int CurrentItem()=0;protected:Interator(){}};class ConcreteInterator:public Interator{public:ConcreteInterator(Aggregate* ag,int index=0){m_ag=ag;m_index=index;}~ConcreteInterator(){}void First(){m_index=0;}void Next(){if(m_index != m_ag->GetSize()) m_index++;}bool IsDone(){return(m_index==m_ag->GetSize());}int CurrentItem(){return m_ag->GetItem(m_index);}private:Aggregate* m_ag;int m_index;};Interator* ConcreteAggregate::CreateItrator(){return new ConcreteInterator(this);}void main(){Aggregate* ag=new ConcreteAggregate();Interator* it=new ConcreteInterator(ag);for(;!(it->IsDone());it->Next()){cout<<it->CurrentItem()<<endl;}delete it;delete ag;}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.