Iterator mode (C ++ iterator mode) and Iterator Mode

Source: Internet
Author: User

Iterator mode (C ++ iterator mode) and Iterator Mode

Basically speaking, the Iterator mode is nothing to say, and there are too many ideas in STL. It is generally used to traverse data structures and its implementation is relatively simple.

 

The Code is as follows:

//////////////////////////////////////////////////////////////////////////// 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;}


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.