stl迭代器模式

来源:互联网 发布:linux读取u盘文件 编辑:程序博客网 时间:2024/05/28 05:15

迭代器(Iterator)模式,又叫做游标(Cursor)模式。GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。 从定义可见,迭代器模式是为容器而生。很明显,对容器对象的访问必然涉及到遍历算法。

最简单的,下面的语句。

vector<int> vec;vector<int>::iterator iter = vec.begin();
在stl_vector.h中
typedef __gnu_cxx::__normal_iterator<pointer, vector> iterator;

vector<int>::iterator就相当于__normal_iterator<int*, vector>,是一个__normal_iterator实例化的对象。

在stl_iterator.h中(注释是我自己写的)

using std::iterator_traits;  using std::iterator;  template<typename _Iterator, typename _Container>    class __normal_iterator    {    protected:      _Iterator _M_current;//与容器的联系      typedef iterator_traits<_Iterator>__traits_type;//iterator_traits<int *>萃取机    public:      typedef _Iteratoriterator_type;//int*      typedef typename __traits_type::iterator_category iterator_category;//random_access_iterator_tag      typedef typename __traits_type::value_type  value_type;//int      typedef typename __traits_type::difference_type difference_type;      typedef typename __traits_type::reference reference;      typedef typename __traits_type::pointer   pointer;...     };
 _M_current这个变量保持了与vector<int>的联系,他的实际类型应该是int*。__normal_iterator这个类模板中实现了迭代器的操作,包括解引用,++,--,[]等。

在stl_iterator.h中,不止有__normal_iterator,还有reverse_iterator,move_iterator,back_insert_iterator,front_insert_iterator。这几个就是迭代器模式图中的具体的迭代器类concreteiterator。同时在stl里,concreteiterator和iterator的关系不是继承,而是组合关系

上一张迭代器模式的结构图。



原创粉丝点击