Iterator (C ++ implementation)

Source: Internet
Author: User

// Iterator. cpp: defines the entry point of the console application.
//

# Include "stdafx. H"
# Include <iostream>

Using namespace STD;

Typedef int data;

Class iterator;

Class Aggregate
{
Public:
Aggregate ()
{
}

Virtual ~ Aggregate ()
{
}

Virtual iterator * createiterator () = 0;
Virtual int getsize () = 0;
Virtual Data getitem (INT index) = 0;

};

Class iterator
{
Public:
Iterator ()
{}
Virtual ~ Iterator ()
{}

Virtual void first () = 0;
Virtual void next () = 0;
Virtual bool isdone () = 0;
Virtual Data currentitem () = 0;
};

Class concreteiterator: Public iterator
{
Public:
Concreteiterator (aggregate * P): m_pconcreteaggregate (P), m_index (0)
{

}
Virtual ~ Concreteiterator ()
{

}

Virtual void first ()
{
M_index = 0;
}
Virtual void next ()
{
If (m_index <m_pconcreteaggregate-> getsize ())
{
M_index ++;
}
}
Virtual bool isdone ()
{
Return m_index = m_pconcreteaggregate-> getsize ();
}
Virtual Data currentitem ()
{
Return m_pconcreteaggregate-> getitem (m_index );
}

PRIVATE:
Aggregate * m_pconcreteaggregate;
Int m_index;

};
Class concreteaggregate: Public Aggregate
{
Public:
Concreteaggregate (INT size): m_size (size)
{
M_pdata = new data [m_size];
For (INT I = 0; I <m_size; I ++)
{
M_pdata [I] = I;
}
}
Virtual ~ Concreteaggregate ()
{
Delete [] m_pdata;
M_pdata = NULL;

}

Virtual iterator * createiterator ()
{
Return new concreteiterator (this );
}

Virtual int getsize ()
{
Return m_size;
}

Virtual Data getitem (INT index)
{
If (index <m_size)
{
Return m_pdata [Index];
}
Else
{
Return-1;
}
}

PRIVATE:
Int m_size;
Data * m_pdata;

};

Int _ tmain (INT argc, _ tchar * argv [])
{
Aggregate * paggregate = new concreteaggregate (10 );
Iterator * piterator = paggregate-> createiterator ();
For (; false = piterator-> isdone (); piterator-> next ())
{
Cout <piterator-> currentitem () <Endl;
}
Return 0;
}

 

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.