迭代器是设计模式中的一种;
迭代器,最基本的操作包括迭代器的++,--,+n,*及->操作;
为了统一迭代器的操作;
STL自带迭代器定义形式如下
template<class Category,
class T,
class Distance = ptrdiaff_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;
// ...
};
迭代器需要定义五个型别
value_type
difference_type
reference_type
pointer_type
interator_category;
举个例子:
iterator<int> ;其中int即为interator<int>的value_type;
iterator<string>;其中string即为interator<string>的value_type;
template <class T>
struct MyIterator {
typedef T value_type;
T * ptr;
T& operator*() const { return *ptr;}
// ...
};
在迭代器上应用函数时,可以通过
template<class I>
typename I::value_type
func(I ite){
return *ite;
}
通过函数func可以获取迭代器中的值;
但是以上实现有一个例外;即是对于原始指针T*,及const T*,就没有了I::value_type的定义;
(众所周知,原始指针也可以当做迭代器使用,sort函数对于原始数组排序依然生效);
为了兼容以上情况,STL引入了iterator_traits;
template<class I>
struct iterator_traits {
typedef typename I::value_type value_type;
};
针对原始指针T*,进行特例化
template<class T>
struct iterator_traits<T*> {
typedef T value_type;
};
针对const T*,进行特例化
template<class T>
struct iterator_traits<const T*> {
typedef T value_type;
};
const T*的value_type去除了const属性,主要是为了方便后续通过value_type定义变量进行使用;
而后将func的定义修改为
template<class I>
typename iterator_traits<I>::value_type
func(I ite){
return *ite;
}
完成以上定义之后,普通的指针(比如int*,int a[10],对应的&a[i])亦可当做迭代器进行处理;从而可以当做参数传给stl中的算法模块进行处理,比如find,sort等算法函数进行处理。

1033

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



