从零开始学C++之STL(三):迭代器类vector::iterator 和 vector::reverse_iterator 的实现、迭代器类型、常用的容器成员

一、迭代器

迭代器是泛型指针

普通指针可以指向内存中的一个地址

迭代器可以指向容器中的一个位置

STL的每一个容器类模版中,都定义了一组对应的迭代器类。使用迭代器,算法函数可以访问容器中指定位置的元素,而无需关心元素的具体类型。



下面来稍微看一下vector<class>::iterator 和 vector<class>::reverse_iterator 的源码:


 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

template <  class _Ty,
          class _Alloc >
class _Vector_val
    :  public _CONTAINER_BASE_AUX_ALLOC<_Alloc>
{
     // base class for vector to hold allocator _Alval
protected:
    _Vector_val(_Alloc _Al = _Alloc())
        : _CONTAINER_BASE_AUX_ALLOC<_Alloc>(_Al), _Alval(_Al)
    {
         // construct allocator from _Al
    }

     typedef  typename _Alloc:: template
    rebind<_Ty>::other _Alty;

    _Alty _Alval;    // allocator object for values
};

template <  class _Ty,
          class _Ax >
class vector
    :  public _Vector_val<_Ty, _Ax>
{
     // varying size array of values
public:
    .....
    typedef _Vector_val<_Ty, _Ax> _Mybase;
    typedef typename _Mybase::_Alty _Alloc;  // _Alloc 的定义所在
     typedef _Vector_iterator<_Ty, _Alloc> iterator;
     typedef _Vector_const_iterator<_Ty, _Alloc> const_iterator;

     //  friend class _Vector_iterator<_Ty, _Alloc>;
     friend  class _Vector_const_iterator<_Ty, _Alloc>;

     typedef std::reverse_iterator<iterator> reverse_iterator;
     typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
    .......
};

template <  class _Ty,
          class _Alloc >
class _Vector_iterator
    :  public _Vector_const_iterator<_Ty, _Alloc>
{
     // iterator for mutable vector
public:
     typedef _Vector_iterator<_Ty, _Alloc> _Myt;
     typedef _Vector_const_iterator<_Ty, _Alloc> _Mybase;
    .......
};

template <  class _Ty,
          class _Alloc >
class _Vector_const_iterator
    :  public _Ranit < _Ty,  typename _Alloc::difference_type,
       typename _Alloc::const_pointer,  typename _Alloc::const_reference >
{
     // itera
  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值