这个模式在stl中是非常之常见,因为迭代器进行元素输出的时候基本都是用这个。。。。。不多说上图
自己实现一个简单的栈,内部友元类是iterator
迭代器初始化mystack;
// Iterator.cpp : 定义控制台应用程序的入口点。
//************************************************************************/
/* @filename Iterator.cpp
@author wallwind
@createtime 2012/10/30 23:58
@function 迭代器模式
@email wochenglin@qq.com
*/
/************************************************************************/
#include "stdafx.h"
#include <iostream>
using namespace std;
enum{MAXSIZE =100,};
//class Iterator;
class MyStackIterator;
class MyStack
{
public:
MyStack()
{
m_top =0;
};
~MyStack()
{
delete[] m_stack;
};
void push(int x)
{
if(m_top>MAXSIZE)
{
return ;
}
m_stack[m_top++] = x;
}
int pop()
{
if(m_top<0)
{
return -1;
}
return m_stack[--m_top];
}
friend class MyStackIterator;
private:
int m_top;
int m_stack[MAXSIZE];
};
class Iterator
{
public:
Iterator(){};
virtual ~Iterator(){};
virtual void Next()=0;
virtual int operator++() = 0;
virtual bool isEnd() = 0;
virtual int currData() = 0;
};
class MyStackIterator : public Iterator
{
public:
MyStackIterator(MyStack* stack)
:m_myStack(stack)
{
m_index = 0;
}
~MyStackIterator()
{
if (m_myStack!=NULL)
{
delete m_myStack;
}
}
virtual int operator++()
{
if (m_index<m_myStack->m_top)
{
return m_myStack->m_stack[m_index++];
}
}
virtual void Next()
{
if (m_index<m_myStack->m_top)
{
m_index++;
}
}
virtual bool isEnd()
{
return m_index <= m_myStack->m_top;
}
virtual int currData()
{
return m_myStack->m_stack[m_index];
}
private:
MyStack * m_myStack;
int m_index;
};
int _tmain(int argc, _TCHAR* argv[])
{
MyStack *mystak = new MyStack();
for (int i = 0; i<6;i++)
{
mystak->push(i);
}
MyStackIterator *myit = new MyStackIterator(mystak);
/**
cout<<(*myit)++<<endl;
myit->Next();
cout<<myit->currData()<<endl;
**/
while (myit->isEnd())
{
cout<<myit->currData()<<endl;
myit->Next();
}
return 0;
}
输出的结果
迭代器的模式非常好玩。。。
更多文章,欢迎访问:http://blog.csdn.net/wallwind