STL源码-迭代器

2019年4月15日 0 条评论 128 次阅读 1 人点赞

完整代码见: LiTianxiong/Standard-Template-Library

迭代器

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_tag :public bidirectional_iterator_tag {};

template <typename Category, typename T, typename Distance = ptrdiff_t, 
typename 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;
    };

迭代器这方面比较简单, 主要的重点是traits编程方式, 在类中定义一系列的typedef, 对于自定义类, 可以使用这些typedef返回需要的类型, 对于内置类型, 如指针, 可以通过模版的具体化, 使其返回相应的类型

具体代码如下, 对于自定义类型, iterator_traits内部直接使用Iterator内部定义的类型, 而对于指针, iterator_traits使用具体化的方式, 使用了自定义的typedef

    template <typename 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;
    };

    template <typename T>
    struct iterator_traits<T*>
    {
        typedef random_access_iterator_tag     iterator_category;
        typedef T                               value_type;
        typedef ptrdiff_t                       difference_type;
        typedef T*                              pointer;
        typedef T&                              reference;
    };    
    
    template <typename T>
    struct iterator_traits<const T*>
    {
        typedef random_access_iterator_tag     iterator_category;
        typedef T                               value_type;
        typedef ptrdiff_t                       difference_type;
        typedef const T*                        pointer;
        typedef const T&                        reference;
    };

litmxs

这个人太懒什么东西都没留下

文章评论(0)