STL源码剖析之Iterator

来源:互联网 发布:linux文件分区 编辑:程序博客网 时间:2024/05/20 14:20

STL源码剖析之Iterator

typename和typedef的含义

typename一般来说用法比较简单,在定义模板的时候声明一个类参数。

template <typename T>class Demo{    T t;};

这个时候typename和class没有任何区别。但是typename还有其他用法。一个类除了有类的成员变量、成员函数之外,还可以有类的定义。

template <class T>class Demo{    T t;public:    typedef T value_type;};

这种定义可以为外部所用,但是必须不能漏掉前缀typename,否则编译器将不知道你所用的是一个类型还是一个变量。

template <class T>class V{    typename T::value_type v; //用别的类内部的typedef定义了一个成员变量};

container和algorithm分隔和联系

STL中一个很重要的思想是把容器和算法区分开来。容器通过模板类来实现,算法通过模板方法来实现。前者有vector,map等等;后者则有sort,distance,find等等。

而沟通两者的桥梁就是iterator。通常algorithm不知道自己的算法是运行在什么样的容器上,但是通过iterator,算法能保证能够遍历容器里面的元素。这就是为什么iterator如此重要。

具体遍历的方法到底是不是由容器实现的呢?

iterator是一种智能指针

什么是智能指针?最直观的表现是:一个普通类持有一个指针,重载了*、->、==、!=、++等运算符,装得很像一个指针一样。

iterator的五种category

分别是InputIterator、OutputIterator、ForwardIterator、BidirectionalIterator和RandomAccessIterator。五种不同的Iterator发挥着不同的作用。这个category不是某个Iterator的字段,而是实实在在的一个类。所以category是模板的类参数之一。

template<typename _Category, typename _Tp, typename _Distance = ptrdiff_t, typename _Pointer = _Tp*, typename _Reference = _Tp&>struct iterator{    /// One of the @link iterator_tags tag types@endlink.    typedef _Category  iterator_category;    /// The type "pointed to" by the iterator.    typedef _Tp        value_type;    /// Distance between iterators is represented as this type.    typedef _Distance  difference_type;    /// This type represents a pointer-to-value_type.    typedef _Pointer   pointer;    /// This type represents a reference-to-value_type.    typedef _Reference reference;};

为什么需要iterator_traits

iterator_traits的出现相当于继续再iterator类的typedef之上封了一层,但是还囊括了原生指针。

源码

0 0
原创粉丝点击