概念:iterator,提供一种方法,使之能够依序巡防某个聚合物(容器)所包含的每个元素,而又无需暴露该容器内部的表达方式。
Stl设计的思想就是把容器和算法分开来,彼此独立,举例就是一个find()算法可以应用于不同的容器对象,
例如vector list deque.stl设计中iterator的作用就是粘合剂,使得算法和容器联系起来。
template<class InputIterator,class T>
InputIterator find(InputIterator first,InputIterator last,const T& value)
{
while(first!=last&&*first!=value)
first++;
return first;
}
Find()应用于不同的容器:
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
const int arraySize=7;
int ia[arraySize]={0,1,2,3,4,5,6};
vector<int> ivect(ia,ia+arraySize);
list<int>ilist(ia,ia+arraySize);
deque<int>ideque(ia,ia+arraySize);
vector<int>::iterator itl=find(ivect.begin(),ivect.end(),4);
if(itl==ivect.end())
cout<<"4 not found"<<endl;
else
cout<<"4 found."<<*itl<<endl;
list<int>::iterator it2=find(ilist.begin(),ilist.end(),6);
if(it2==ilist.end())
cout<<"6 not found."<<endl;
else
cout<<"6 found.!"<<*it2<<endl;
deque<int>::iterator it3=find(ideque.begin(),ideque.end(),8);
if(it3==ideque.end())
cout<<"8 not found."<<endl;
else
cout<<"8found."<<*it3<<endl;
cin.get();
return 0;
}
<p>iterator是一种类似于指针的对象。它的最重要工作就是对operator*和operator->进行重载,</p><p>下面来为list设计一个迭代器:</p><p>假设list及其节点结构如下:</p><pre name="code" class="cpp">template <typename T>
class List
{
void insert_front(T value);
void insert_back(T value);
void display(....)const;
....
private:
ListItem<T> *end;
ListItem<T> *front;
long size;
}
template<typename T>
class ListItem
{
public:
T value()const{return value;}
ListItem* next()const{return next;}
private:
T value;
ListItem *next;
}
如何套用先前的find()的函数,需要为它设计一个类似于行为指针的外衣。也就是一个迭代器。当我们提领这一迭代器时,返回一个ListItem对象;
当我们递增该迭代器时,指向下一个ListItem对象。为了让该迭代器适用用任何型态的节点,而不限于ListItem对象,我们可以把它设计为class template。
template<class Item>
struct ListIter
{
Item *ptr;
ListIter(Item* p=0):ptr(p){}
Item& operator*()const{return *ptr;}
Item* operator->()const{return ptr;}
ListIter operator++(int)
{ListIter tmp=*this;++*this;return tmp;}
bool operator==(const ListIter& i)const
{return ptr==i.ptr;}
bool operator!=(const ListIter& I)const
{return ptr!=i.ptr;}
};
<p>现在可以将List和find()由ListIter粘合起来 :图1和图2<img src="https://img-blog.csdn.net/20141203151536437?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY293MDM3Nw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></p>
这样的设计暴露了太多list和listiter的设计细节。如果换做他人,你必须对list和listiter的设计细节很熟悉才能设计出来这样的迭代器。所以就把迭代器的设计交给了list的设计者,所有的细节得以封装而不被使用者看到,这也是每一种stl容器都提供有专属迭代器的缘故。
下一篇讲解迭代器的相应型别和traits变成技巧