Iterator模式,也称为迭代器模式。
该模式主要用于将列表的访问和遍历分离出来并放进一个迭代器中。例如STL库的容器就大量的用到Iterator模式。
该模式还涉及到一些“内部迭代器”和“外部迭代器”的概念,这属于进一步的研究,暂时不谈。
下面看看简单的例子代码(模仿STL的做法):
// Iterator.cpp
#include
<
iostream
>
using namespace std;
class ArrayList
{
public:
typedef int* Iterator;
ArrayList()
{
cnt = 0;
}
// 这里可以看出来Iterator实际上是一个 int* 类型的指针
Iterator Begin()
{
return &arr[0];
}
Iterator End()
{
return &arr[cnt];
}
void Insert(int v)
{
if(cnt >= 100 )
{
cout << "列表容量已满,不可再插入。" << endl;
return;
}
arr[cnt] = v;
cnt++;
}
private:
int cnt;
int arr[100];
} ;
void main()
{
ArrayList list;
for(int i = 0; i < 110; i++)
{
list.Insert(i);
}
ArrayList::Iterator it;
for (it = list.Begin(); it != list.End(); it++)
{
cout << *it << endl;
}
}
using namespace std;
class ArrayList
{
public:
typedef int* Iterator;
ArrayList()
{
cnt = 0;
}
// 这里可以看出来Iterator实际上是一个 int* 类型的指针
Iterator Begin()
{
return &arr[0];
}
Iterator End()
{
return &arr[cnt];
}
void Insert(int v)
{
if(cnt >= 100 )
{
cout << "列表容量已满,不可再插入。" << endl;
return;
}
arr[cnt] = v;
cnt++;
}
private:
int cnt;
int arr[100];
} ;
void main()
{
ArrayList list;
for(int i = 0; i < 110; i++)
{
list.Insert(i);
}
ArrayList::Iterator it;
for (it = list.Begin(); it != list.End(); it++)
{
cout << *it << endl;
}
}