STL源码剖析之序列容器list

来源:互联网 发布:淘宝试用协议在pc端哪 编辑:程序博客网 时间:2024/05/22 11:27

一、定义

容器list的特点是每次插入一个元素就配置一个空间,每次删除一个元素就释放一个空间。结构定义如下:

struct _List_node_base {  _List_node_base* _M_next;//后继指针  _List_node_base* _M_prev;//前驱指针};template <class _Tp>struct _List_node : public _List_node_base {  _Tp _M_data; //数据域};
由此可见,list底层是一个双向链表。

与vector的区别:

(1)vector分配的是一块连续的地址空间,随机访问效率高;list为离散的地址空间,插入删除效率高。

(2)vector底层为内存可扩展的数组,list底层为双向链表。

(3)vector迭代器支持自增自减以及其他算术运算,list除了自增自减不能支持其他算术运算。

(4)vector的插入删除或导致元素的重新配置,原有迭代器会失效;list的插入不会造成原有迭代器的失效,删除只是指向删除位置的迭代器失效。

二、list迭代器

struct _List_iterator_base {  typedef size_t                     size_type;  typedef ptrdiff_t                  difference_type;  typedef bidirectional_iterator_tag iterator_category;//迭代器设计为双向迭代器  _List_node_base* _M_node;//指向list结点的指针  _List_iterator_base(_List_node_base* __x) : _M_node(__x) {}//构造函数  _List_iterator_base() {}  void _M_incr() { _M_node = _M_node->_M_next; }  void _M_decr() { _M_node = _M_node->_M_prev; }  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; }//取结点数据值#ifndef __SGI_STL_NO_ARROW_OPERATOR  pointer operator->() const { return &(operator*()); }#endif /* __SGI_STL_NO_ARROW_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;  }};#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION//如果编译器不支持偏特化inline bidirectional_iterator_tagiterator_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;}#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
三、list的内存管理

template <class _Tp, class _Allocator, bool _IsStatic>class _List_alloc_base {public:  typedef typename _Alloc_traits<_Tp, _Allocator>::allocator_type//获取类型          allocator_type;  allocator_type get_allocator() const { return _Node_allocator; }  _List_alloc_base(const allocator_type& __a) : _Node_allocator(__a) {}//构造函数protected:  _List_node<_Tp>* _M_get_node()//获取一个节点   { return _Node_allocator.allocate(1); }  void _M_put_node(_List_node<_Tp>* __p)//删除一个节点    { _Node_allocator.deallocate(__p, 1); }protected:  typename _Alloc_traits<_List_node<_Tp>, _Allocator>::allocator_type           _Node_allocator;//定义空间配置器  _List_node<_Tp>* _M_node;//定义一个指针};// 空间配置器的一个特例化template <class _Tp, class _Allocator>class _List_alloc_base<_Tp, _Allocator, true> {public:  typedef typename _Alloc_traits<_Tp, _Allocator>::allocator_type          allocator_type;  allocator_type get_allocator() const { return allocator_type(); }  _List_alloc_base(const allocator_type&) {}protected:  typedef typename _Alloc_traits<_List_node<_Tp>, _Allocator>::_Alloc_type          _Alloc_type;  _List_node<_Tp>* _M_get_node() { return _Alloc_type::allocate(1); }  void _M_put_node(_List_node<_Tp>* __p) { _Alloc_type::deallocate(__p, 1); }protected:  _List_node<_Tp>* _M_node;};//list的基类template <class _Tp, class _Alloc>class _List_base   : public _List_alloc_base<_Tp, _Alloc,                            _Alloc_traits<_Tp, _Alloc>::_S_instanceless>{public:  typedef _List_alloc_base<_Tp, _Alloc,                           _Alloc_traits<_Tp, _Alloc>::_S_instanceless>          _Base; //定义一个基类类型  typedef typename _Base::allocator_type allocator_type;  _List_base(const allocator_type& __a) : _Base(__a) {//构造函数    _M_node = _M_get_node();//获取节点    _M_node->_M_next = _M_node;//环形链表    _M_node->_M_prev = _M_node;  }  ~_List_base() {//析构函数    clear();    _M_put_node(_M_node);  }  void clear();};#else /*使用标准空间配置器 */template <class _Tp, class _Alloc>class _List_base {public:  typedef _Alloc allocator_type;  allocator_type get_allocator() const { return allocator_type(); }  _List_base(const allocator_type&) {    _M_node = _M_get_node();    _M_node->_M_next = _M_node;    _M_node->_M_prev = _M_node;  }  ~_List_base() {    clear();    _M_put_node(_M_node);  }  void clear();protected:  typedef simple_alloc<_List_node<_Tp>, _Alloc> _Alloc_type;  _List_node<_Tp>* _M_get_node() { return _Alloc_type::allocate(1); }//申请结点  void _M_put_node(_List_node<_Tp>* __p) { _Alloc_type::deallocate(__p, 1); } //释放节点protected:  _List_node<_Tp>* _M_node;//指向链表指针};

四、list的源码

template <class _Tp, class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >class list : protected _List_base<_Tp, _Alloc> {  __STL_CLASS_REQUIRES(_Tp, _Assignable);  typedef _List_base<_Tp, _Alloc> _Base;//定义基类类型protected:  typedef void* _Void_pointer;//定义一个指针public:        typedef _Tp value_type;  typedef value_type* pointer;  typedef const value_type* const_pointer;  typedef value_type& reference;  typedef const value_type& const_reference;  typedef _List_node<_Tp> _Node;  typedef size_t size_type;  typedef ptrdiff_t difference_type;  typedef typename _Base::allocator_type allocator_type;  allocator_type get_allocator() const { return _Base::get_allocator(); }public:  typedef _List_iterator<_Tp,_Tp&,_Tp*>             iterator;//定义一个迭代器  typedef _List_iterator<_Tp,const _Tp&,const _Tp*> const_iterator;#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION  typedef reverse_iterator<const_iterator> const_reverse_iterator;  typedef reverse_iterator<iterator>       reverse_iterator;#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */  typedef reverse_bidirectional_iterator<const_iterator,value_type,                                         const_reference,difference_type>          const_reverse_iterator;  typedef reverse_bidirectional_iterator<iterator,value_type,reference,                                         difference_type>          reverse_iterator; #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */protected:#ifdef __STL_HAS_NAMESPACES  using _Base::_M_node;  using _Base::_M_put_node;  using _Base::_M_get_node;#endif /* __STL_HAS_NAMESPACES */protected:  _Node* _M_create_node(const _Tp& __x)//创建一个节点  {    _Node* __p = _M_get_node();    __STL_TRY {      _Construct(&__p->_M_data, __x);//初始化空间    }    __STL_UNWIND(_M_put_node(__p));    return __p;  }  _Node* _M_create_node()  {    _Node* __p = _M_get_node();    __STL_TRY {      _Construct(&__p->_M_data);    }    __STL_UNWIND(_M_put_node(__p));    return __p;  }public:  explicit list(const allocator_type& __a = allocator_type()) : _Base(__a) {}//构造函数  iterator begin()             { return (_Node*)(_M_node->_M_next); }//获得第一个元素位置  const_iterator begin() const { return (_Node*)(_M_node->_M_next); }  iterator end()             { return _M_node; }//获得最后一个标志位(list为双向链表)  const_iterator end() const { return _M_node; }  reverse_iterator rbegin() //反向迭代器    { return reverse_iterator(end()); }  const_reverse_iterator rbegin() const     { return const_reverse_iterator(end()); }  reverse_iterator rend()    { return reverse_iterator(begin()); }  const_reverse_iterator rend() const    { return const_reverse_iterator(begin()); }  bool empty() const { return _M_node->_M_next == _M_node; }//判断是否为空  size_type size() const {     //获得元素个数    size_type __result = 0;    distance(begin(), end(), __result);    return __result;  }  size_type max_size() const { return size_type(-1); }  reference front() { return *begin(); }//访问第一个元素  const_reference front() const { return *begin(); }  reference back() { return *(--end()); }//访问最后一个元素  const_reference back() const { return *(--end()); }  void swap(list<_Tp, _Alloc>& __x) { __STD::swap(_M_node, __x._M_node); }//交换两个list  iterator insert(iterator __position, const _Tp& __x) {//在指定位置插入元素    _Node* __tmp = _M_create_node(__x);    __tmp->_M_next = __position._M_node;    __tmp->_M_prev = __position._M_node->_M_prev;    __position._M_node->_M_prev->_M_next = __tmp;    __position._M_node->_M_prev = __tmp;    return __tmp;  }  iterator insert(iterator __position) { return insert(__position, _Tp()); }#ifdef __STL_MEMBER_TEMPLATES  // Check whether it's an integral type.  If so, it's not an iterator.  template<class _Integer>  void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __x,                          __true_type) {    _M_fill_insert(__pos, (size_type) __n, (_Tp) __x);  }  template <class _InputIterator>  void _M_insert_dispatch(iterator __pos,                          _InputIterator __first, _InputIterator __last,                          __false_type);  template <class _InputIterator>  void insert(iterator __pos, _InputIterator __first, _InputIterator __last) {    typedef typename _Is_integer<_InputIterator>::_Integral _Integral;    _M_insert_dispatch(__pos, __first, __last, _Integral());  }#else /* __STL_MEMBER_TEMPLATES */  void insert(iterator __position, const _Tp* __first, const _Tp* __last);  void insert(iterator __position,              const_iterator __first, const_iterator __last);#endif /* __STL_MEMBER_TEMPLATES */  void insert(iterator __pos, size_type __n, const _Tp& __x)    { _M_fill_insert(__pos, __n, __x); }  void _M_fill_insert(iterator __pos, size_type __n, const _Tp& __x);   void push_front(const _Tp& __x) { insert(begin(), __x); }//在表头插入元素  void push_front() {insert(begin());}  void push_back(const _Tp& __x) { insert(end(), __x); }//在表尾插入元素  void push_back() {insert(end());}  iterator erase(iterator __position) {//删除某位置元素    _List_node_base* __next_node = __position._M_node->_M_next;    _List_node_base* __prev_node = __position._M_node->_M_prev;    _Node* __n = (_Node*) __position._M_node;    __prev_node->_M_next = __next_node;    __next_node->_M_prev = __prev_node;    _Destroy(&__n->_M_data);    _M_put_node(__n);    return iterator((_Node*) __next_node);  }  iterator erase(iterator __first, iterator __last);//删除区间元素  void clear() { _Base::clear(); }  void resize(size_type __new_size, const _Tp& __x);//重置大小  void resize(size_type __new_size) { this->resize(__new_size, _Tp()); }  void pop_front() { erase(begin()); }//删除头部元素  void pop_back() { //删除尾部元素    iterator __tmp = end();    erase(--__tmp);  }  list(size_type __n, const _Tp& __value,       const allocator_type& __a = allocator_type())    : _Base(__a)    { insert(begin(), __n, __value); }  explicit list(size_type __n)    : _Base(allocator_type())    { insert(begin(), __n, _Tp()); }#ifdef __STL_MEMBER_TEMPLATES  // We don't need any dispatching tricks here, because insert does all of  // that anyway.    template <class _InputIterator>  list(_InputIterator __first, _InputIterator __last,       const allocator_type& __a = allocator_type())    : _Base(__a)    { insert(begin(), __first, __last); }#else /* __STL_MEMBER_TEMPLATES */  list(const _Tp* __first, const _Tp* __last,       const allocator_type& __a = allocator_type())    : _Base(__a)    { this->insert(begin(), __first, __last); }  list(const_iterator __first, const_iterator __last,       const allocator_type& __a = allocator_type())    : _Base(__a)    { this->insert(begin(), __first, __last); }#endif /* __STL_MEMBER_TEMPLATES */  list(const list<_Tp, _Alloc>& __x) : _Base(__x.get_allocator())//拷贝函数    { insert(begin(), __x.begin(), __x.end()); }  ~list() { }//析构函数  list<_Tp, _Alloc>& operator=(const list<_Tp, _Alloc>& __x);//赋值运算符重在public:  void splice(iterator __position, list& __x) {//list分割函数    if (!__x.empty())       this->transfer(__position, __x.begin(), __x.end());  }  void splice(iterator __position, list&, iterator __i) {    iterator __j = __i;    ++__j;    if (__position == __i || __position == __j) return;    this->transfer(__position, __i, __j);  }  void splice(iterator __position, list&, iterator __first, iterator __last) {    if (__first != __last)       this->transfer(__position, __first, __last);  }  void remove(const _Tp& __value);  void unique();  void merge(list& __x);  void reverse();  void sort();};template <class _Tp, class _Alloc>inline bool operator==(const list<_Tp,_Alloc>& __x, const list<_Tp,_Alloc>& __y)//运算符==的重载{  typedef typename list<_Tp,_Alloc>::const_iterator const_iterator;  const_iterator __end1 = __x.end();  const_iterator __end2 = __y.end();  const_iterator __i1 = __x.begin();  const_iterator __i2 = __y.begin();  while (__i1 != __end1 && __i2 != __end2 && *__i1 == *__i2) {    ++__i1;    ++__i2;  }  return __i1 == __end1 && __i2 == __end2;}template <class _Tp, class _Alloc>inline bool operator<(const list<_Tp,_Alloc>& __x,//运算符<的重载                      const list<_Tp,_Alloc>& __y){  return lexicographical_compare(__x.begin(), __x.end(),                                 __y.begin(), __y.end());}template <class _Tp, class _Alloc>void list<_Tp, _Alloc>::remove(const _Tp& __value)//移除某个元素{  iterator __first = begin();  iterator __last = end();  while (__first != __last) {    iterator __next = __first;    ++__next;    if (*__first == __value) erase(__first);    __first = __next;  }}template <class _Tp, class _Alloc>void list<_Tp, _Alloc>::unique()//移除相同元素{  iterator __first = begin();  iterator __last = end();  if (__first == __last) return;  iterator __next = __first;  while (++__next != __last) {    if (*__first == *__next)      erase(__next);    else      __first = __next;    __next = __first;  }}template <class _Tp, class _Alloc>void list<_Tp, _Alloc>::merge(list<_Tp, _Alloc>& __x)//两个list的合并{  iterator __first1 = begin();  iterator __last1 = end();  iterator __first2 = __x.begin();  iterator __last2 = __x.end();  while (__first1 != __last1 && __first2 != __last2)    if (*__first2 < *__first1) {      iterator __next = __first2;      transfer(__first1, __first2, ++__next);      __first2 = __next;    }    else      ++__first1;  if (__first2 != __last2) transfer(__last1, __first2, __last2);}inline void __List_base_reverse(_List_node_base* __p)//链表内容转置{  _List_node_base* __tmp = __p;  do {    __STD::swap(__tmp->_M_next, __tmp->_M_prev);    __tmp = __tmp->_M_prev;     // 原来的后继结点变成前驱  } while (__tmp != __p);}template <class _Tp, class _Alloc>inline void list<_Tp, _Alloc>::reverse() {  __List_base_reverse(this->_M_node);}    template <class _Tp, class _Alloc>void list<_Tp, _Alloc>::sort()//排序{  if (_M_node->_M_next != _M_node && _M_node->_M_next->_M_next != _M_node) {    list<_Tp, _Alloc> __carry;    list<_Tp, _Alloc> __counter[64];    int __fill = 0;    while (!empty()) {      __carry.splice(__carry.begin(), *this, begin());      int __i = 0;      while(__i < __fill && !__counter[__i].empty()) {        __counter[__i].merge(__carry);        __carry.swap(__counter[__i++]);      }      __carry.swap(__counter[__i]);               if (__i == __fill) ++__fill;    }     for (int __i = 1; __i < __fill; ++__i)      __counter[__i].merge(__counter[__i-1]);    swap(__counter[__fill-1]);  }}#ifdef __STL_MEMBER_TEMPLATEStemplate <class _Tp, class _Alloc> template <class _Predicate>void list<_Tp, _Alloc>::remove_if(_Predicate __pred)//移除满足条件的元素{  iterator __first = begin();  iterator __last = end();  while (__first != __last) {    iterator __next = __first;    ++__next;    if (__pred(*__first)) erase(__first);    __first = __next;  }}template <class _Tp, class _Alloc> template <class _BinaryPredicate>void list<_Tp, _Alloc>::unique(_BinaryPredicate __binary_pred)//移除数值相同的元素{  iterator __first = begin();  iterator __last = end();  if (__first == __last) return;//链表为空  iterator __next = __first;  while (++__next != __last) {    if (__binary_pred(*__first, *__next))      erase(__next);//数值相同移除后面的一个    else      __first = __next;    __next = __first;  }}template <class _Tp, class _Alloc> template <class _StrictWeakOrdering>//两个链表的合并函数void list<_Tp, _Alloc>::merge(list<_Tp, _Alloc>& __x,                              _StrictWeakOrdering __comp)//comp为合并策略{  iterator __first1 = begin();  iterator __last1 = end();  iterator __first2 = __x.begin();  iterator __last2 = __x.end();  while (__first1 != __last1 && __first2 != __last2)    if (__comp(*__first2, *__first1)) {      iterator __next = __first2;      transfer(__first1, __first2, ++__next);      __first2 = __next;    }    else      ++__first1;  if (__first2 != __last2) transfer(__last1, __first2, __last2);}template <class _Tp, class _Alloc> template <class _StrictWeakOrdering>void list<_Tp, _Alloc>::sort(_StrictWeakOrdering __comp)//排序函数{  if (_M_node->_M_next != _M_node && _M_node->_M_next->_M_next != _M_node) {//确保链表不为空且元素大于1    list<_Tp, _Alloc> __carry;    list<_Tp, _Alloc> __counter[64];    int __fill = 0;    while (!empty()) {      __carry.splice(__carry.begin(), *this, begin());      int __i = 0;      while(__i < __fill && !__counter[__i].empty()) {        __counter[__i].merge(__carry, __comp);        __carry.swap(__counter[__i++]);      }      __carry.swap(__counter[__i]);               if (__i == __fill) ++__fill;    }     for (int __i = 1; __i < __fill; ++__i)       __counter[__i].merge(__counter[__i-1], __comp);    swap(__counter[__fill-1]);  }}







0 0