一、迭代器
迭代器是泛型指针
普通指针可以指向内存中的一个地址
迭代器可以指向容器中的一个位置
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 |