要实现const迭代器首先要实现普通迭代器,普通迭代器主要是要实现他的解引用、后置加加等操作符,他的底层是指针,但是不是原生指针,是通过用一个类进行封装,通过对类进行传参数来解决问题,先定义链表的结点
- template<class T>
- struct __list_node
- {
- __list_node
* _prev; - __list_node
* _next; - T _val;
- __list_node(const T& x)
- :_prev(nullptr)
- , _next(nullptr)
- , _val(x)
- {}
- __list_node()
- :_prev(nullptr)
- , _next(nullptr)
- {}
-
- };
接下来是实现list类
- template<class T>
- class list
- {
- typedef __list_node
Node; - public:
- typedef __list_iterator
iterator; - typedef __list_iterator
const T&, const T*> const_iterator; -
- list()
- {
- _head = new Node;
- _head->_prev = _head;
- _head->_next = _head;
- }
- ~list()
- {
- clear();
- delete _head;
- _head = nullptr;
- }
- iterator begin()
- {
- return iterator(_head->_next);
- }
- iterator end()
- {
- return iterator(_head);
- }
- const_iterator begin()const
- {
- return const_iterator(_head->_next);
- }
- const_iterator end()const
- {
- return const_iterator(_head);
- }
- private:
- Node* _head;
- };
在这里面我用了三个模板参数去传递,这为之后定义const迭代器埋下了伏笔,接下来实现普通迭代器
- template<class T,class Ref,class Ptr>
- struct __list_iterator
- {
- typedef __list_node
Node; - typedef __list_iterator
Self; - Node* _node;
- __list_iterator(Node* node)
- :_node(node)
- {}
- //*it
- Ref operator*()
- {
- return _node->_val;
- }
- //++it
- Self& operator++()
- {
- _node = _node->_next;
- return *this;
- }
- //it++
- Self operator++(int)
- {
- Self tmp = *this;
- //_node = _node->_next;
- ++(*this);
- return tmp;
- }
- Self& operator--()
- {
- _node = _node->_prev;
- return *this;
-
- }
- Self operator--(int)
- {
- Self tmp = *this;
- //_node = _node->_prev;
- --(*this);
- return tmp;
- }
- Ptr operator->()
- {
- return &_node->_val;
- }
- bool operator!=(const Self& it)
- {
- return _node != it._node;
- }
-
- };
在这个迭代器类中,我们定义了三个模板参数,其中第一个是为了传递list存放数据的类型,接下来两个是为了定义接下来的const迭代器在通过list代码中我们可以知道const迭代器传了两个const对象过去,通过传const对象去获得const迭代器,并且通过返回值来是返回的也是const对象,这就是const迭代器的封装类。