一。概念
1)迭代器在设计模式中成为iterator模式,其定义为:提供一种方法,使他能够按顺序遍历某个聚合体(容器)所包含的所有元素,但又不需要暴露该容器的内部表现方式。
2)迭代器是一种类似指针的对象,他的工作也主要是内容提取(dereference)和成员的访问(member access)。因此其对应的两个重载操作符工作是:operator*和operator-> 。
二。常用迭代器类型
最常用的迭代器类型包括:value type, difference type, pointer, reference, iterator catagoly.
1)value type,是指迭代器所指对象的类型。
2)difference type,用来表示两个迭代器之间的距离,也可以表示一个容器的最大值。
3)reference type,意为迭代器所指之物的内容。在C++中如果函数要传回左值,都是以by reference的方式进行的。
4)pointer type,指向迭代器所指之物。在C++中,可以实现传回一个左值,令他代表pointer所指之物的地址。
5)iterator_category,表示迭代器的相应类型。在这之前,讨论迭代起器的分类:
a. input iterator:该迭代器所指的对象不允许被外部改变,read only。
b. output iterator:只允许写操作,write only。
c. forward iterator:允许“写入型”的算法在此迭代器内进行读写操作。
d. bidirectional iterator:提供双向移动操作。
e. random access iterator: 增加指针算术能力。例如 ptr+n, ptr[n], ptr1-ptr2, ptr1<ptr2。
三。迭代器定义源码
//五种迭代器类型 struct input_iterator_tag {}; struct output_iterator_tag {}; struct forward_iterator_tag : public input_iterator_tag {}; struct bidirectional_iterator_tag : public forward_iterator_tag {}; struct random_access_iterator_iterator_tag : public bidirectional_iterator_tag {}; //std::iterator.自定义的迭代器应当继承下面这个iterator template <class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> struct iterator { typedef Category iterator_category; typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; }; //特性萃取,获取各个迭代器的相应类型 template <class Iterator> struct iterator_traits { typedef typename Iterator::iterator_category iterator_category; typedef typename Iterator::value_type value_type; typedef typename Iterator::difference_type difference_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference; };
参考资料:《STL源码剖析》华中科大出版社
626

被折叠的 条评论
为什么被折叠?



