STL LIST实现

来源:互联网 发布:安徽财经大学网络选课 编辑:程序博客网 时间:2024/05/29 19:33

struct _List_node_base {
  _List_node_base* _M_next;
  _List_node_base* _M_prev;
};  //定义一个list的node的base class,包含一个指向前node和后node的pointer!

template <class _Tp>
struct _List_node : public _List_node_base {
  _Tp _M_data;
};  //泛化node中包含的数据.

struct _List_iterator_base {
  typedef size_t                     size_type;
  typedef ptrdiff_t                  difference_type;
  typedef bidirectional_iterator_tag iterator_category;  //iterator的特征
  _List_node_base* _M_node;  //通过包含node pointer来完成iterator模仿pointer

  _List_iterator_base(_List_node_base* __x) : _M_node(__x) {}  
  _List_iterator_base() {}

  void _M_incr() { _M_node = _M_node->_M_next; }  //模仿pointer的前进
  void _M_decr() { _M_node = _M_node->_M_prev; }  //模仿pointer的后退

  bool operator==(const _List_iterator_base& __x) const {
    return _M_node == __x._M_node;
  }
  bool operator!=(const _List_iterator_base& __x) const {
    return _M_node != __x._M_node;
  }
}; 

template<class _Tp, class _Ref, class _Ptr>
struct _List_iterator : public _List_iterator_base {
  typedef _List_iterator<_Tp,_Tp&,_Tp*>             iterator;
  typedef _List_iterator<_Tp,const _Tp&,const _Tp*> const_iterator;
  typedef _List_iterator<_Tp,_Ref,_Ptr>             _Self;

  typedef _Tp value_type;
  typedef _Ptr pointer;
  typedef _Ref reference;
  typedef _List_node<_Tp> _Node;

  _List_iterator(_Node* __x) : _List_iterator_base(__x) {}
  _List_iterator() {}
  _List_iterator(const iterator& __x) : _List_iterator_base(__x._M_node) {}

  reference operator*() const { return ((_Node*) _M_node)->_M_data; }

  pointer operator->() const { return &(operator*()); }

  _Self& operator++() {
    this->_M_incr();
    return *this;
  }
  _Self operator++(int) {
    _Self __tmp = *this;
    this->_M_incr();
    return __tmp;
  }
  _Self& operator--() {
    this->_M_decr();
    return *this;
  }
  _Self operator--(int) {
    _Self __tmp = *this;
    this->_M_decr();
    return __tmp;
  }
};
inline bidirectional_iterator_tag
iterator_category(const _List_iterator_base&)
{
  return bidirectional_iterator_tag();
}

template <class _Tp, class _Ref, class _Ptr>
inline _Tp*
value_type(const _List_iterator<_Tp, _Ref, _Ptr>&)
{
  return 0;
}

inline ptrdiff_t*
distance_type(const _List_iterator_base&)
{
  return 0;
}

原创粉丝点击