首页 > 代码库 > STL源码剖析 容器 stl_list.h

STL源码剖析 容器 stl_list.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


list

----------------------------------------------------------------------
??为什么很多在算法库里有的算法还要在类的成员函数里重新实现一遍?
-->1.因为算法库里的是通用的,对于具体的类来说效率不高。
比如说 reverse 如果直接用 stl_algo.h 里的 reverse,会再调用 iter_swap,
而 iter_swap 的实现方法是借用临时变量来交换两个迭代器指向的元素,这样会调用
好几次构造函数、拷贝方法、析构函数。对于双向链表来说,这完全不需要,只需调整
指针的指向就可以了,所以针对具体的数据结构类,如果通用的算法效率不高时要设计自己的成员函数
-->2.另一个原因是算法库里的算法可能限制迭代器必须是某一类迭代器。
比如 STL 里的 sort() 只接受 RandomAccessItertor, 而 list 的迭代器只是 BidirectionalIterator
描述:
1.概述
不仅是双向链表,而且还是一个环状双向链表
2.迭代器
不能像 vector 一样以普通指针作为迭代器,因为其节点不保证在存储空间中连续存在
list 迭代器是 Bidirectional Iterators
不像 vector , list的插入操作和接合操作(splice)都不会造成原有的 list 迭代器失效
3.数据结构
环状链表只需一个标记,即可完全表示整个链表。只要文章在环状链表的尾端加上一个空白节点,
便符合 STL 规范之"前闭后开"区间。


示例1:
list<int> L;
L.push_back(0);
L.push_front(1);
L.insert(++L.begin(), 2);
copy(L.begin(), L.end(), ostream_iterator<int>(cout, " "));
// The values that are printed are 1 2 0
示例2:
#include <iostream>
#include <iterator>
#include <list>
#include <numeric>
#include <algorithm>


using namespace std;


list<int> mylist1, mylist2;


void display(){
	cout << "-------------------------------------------------------" << endl;
	copy(mylist1.begin(), mylist1.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	copy(mylist2.begin(), mylist2.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
}


int main(){
	list<int>::iterator it;
	for(int i = 1; i <= 4; i++) mylist1.push_back(i); //1 2 3 4
	for(int i = 1; i <= 3; i++) mylist2.push_back(i * 10); // 10 20 30
	it = mylist1.begin();
	++it; // it 指向元素 2
	display();
	mylist1.splice(it, mylist2);
	display();	
	/* mylist1: 1 10 20 30 2 3 4 
	   mylist2: 空
	   it 还是指向元素 2
	*/					
	mylist2.splice(mylist2.begin(), mylist1, it);
	display();
	/* mylist1: 1 10 20 30 3 4 
	   mylist2: 2
	   it 现在 invalid 
	*/					


	it = mylist1.begin();
	advance(it, 3);
	mylist1.splice(mylist1.begin(), mylist1, it, mylist1.end());
	display();
	it = mylist1.begin();
	advance(it, 3);
	list<int>::iterator pos = mylist1.begin();
	advance(pos,4);
	mylist1.splice(pos, mylist1, it, mylist1.end()); //出错了,position 不能位于 [first, last) 之内 --> 感觉这样设计不好,不能编译期提醒,至少要在运行期提醒吧。。。
	display();
	
}


源码:
#ifndef __SGI_STL_INTERNAL_LIST_H
#define __SGI_STL_INTERNAL_LIST_H


__STL_BEGIN_NAMESPACE


#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#endif


//list的节点,这是一个双向链表
template <class T>
struct __list_node {
  typedef void* void_pointer;
  void_pointer next;
  void_pointer prev;
  T data;
};
//list迭代器的设计。(vector的迭代器不需要单独设计,用原生指针就可以)
template<class T, class Ref, class Ptr>
struct __list_iterator {
  typedef __list_iterator<T, T&, T*>             iterator;
  typedef __list_iterator<T, const T&, const T*> const_iterator;
  typedef __list_iterator<T, Ref, Ptr>           self;


  typedef bidirectional_iterator_tag iterator_category;
  typedef T value_type;
  typedef Ptr pointer;
  typedef Ref reference;
  typedef __list_node<T>* link_type;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;


  link_type node; // 指向 list 节点的指针


  __list_iterator(link_type x) : node(x) {}
  __list_iterator() {}
  __list_iterator(const iterator& x) : node(x.node) {}


  bool operator==(const self& x) const { return node == x.node; }
  bool operator!=(const self& x) const { return node != x.node; }
  //取节点的数据值
  reference operator*() const { return (*node).data; }


#ifndef __SGI_STL_NO_ARROW_OPERATOR
  pointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */


  //迭代器累加 1, 前进一个节点
  self& operator++() { 
    node = (link_type)((*node).next);
	// 因为 __list_node 里的 prev 和 next 的类型是 void * ,
	//所以还要将它们显示转换为 link_type 类型,即 __list_node * 类型
    return *this;
  }
  self operator++(int) { 
    self tmp = *this;
    ++*this;
    return tmp;
  }
  //迭代器递减 1,后退一个节点
  self& operator--() { 
    node = (link_type)((*node).prev);
    return *this;
  }
  self operator--(int) { 
    self tmp = *this;
    --*this;
    return tmp;
  }
};


#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION


template <class T, class Ref, class Ptr>
inline bidirectional_iterator_tag
iterator_category(const __list_iterator<T, Ref, Ptr>&) {
  return bidirectional_iterator_tag();
}


template <class T, class Ref, class Ptr>
inline T*
value_type(const __list_iterator<T, Ref, Ptr>&) {
  return 0;
}


template <class T, class Ref, class Ptr>
inline ptrdiff_t*
distance_type(const __list_iterator<T, Ref, Ptr>&) {
  return 0;
}


#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */


//list的数据结构
template <class T, class Alloc = alloc>
class list {
protected:
  typedef void* void_pointer;
  typedef __list_node<T> list_node;
  //空间配置器,每次配置一个节点大小
  typedef simple_alloc<list_node, Alloc> list_node_allocator;
public:      
  typedef T 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* link_type;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;


public:
  typedef __list_iterator<T, T&, T*>             iterator;
  typedef __list_iterator<T, const T&, const T*> 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:
  //配置一个节点并传回
  link_type get_node() { return list_node_allocator::allocate(); }
  //释放 p 指向的节点空间
  void put_node(link_type p) { list_node_allocator::deallocate(p); }
  //配置并构造一个节点使它的值为 x
  link_type create_node(const T& x) {
    link_type p = get_node();
    __STL_TRY {
      construct(&p->data, x);
    }
    __STL_UNWIND(put_node(p));
    return p;
  }
  //析构并释放一个节点
  void destroy_node(link_type p) {
    destroy(&p->data);
    put_node(p);
  }


protected:
  void empty_initialize() { 
    node = get_node(); //配置一个节点空间,令 node 指向它
    node->next = node; // 令 node 的头尾都指向自己,不设元素值
    node->prev = node;
  }


  void fill_initialize(size_type n, const T& value) {
    empty_initialize();
    __STL_TRY {
      insert(begin(), n, value);
    }
    __STL_UNWIND(clear(); put_node(node));
  }


#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  void range_initialize(InputIterator first, InputIterator last) {
    empty_initialize();
    __STL_TRY {
      insert(begin(), first, last);
    }
    __STL_UNWIND(clear(); put_node(node));
  }
#else  /* __STL_MEMBER_TEMPLATES */
  void range_initialize(const T* first, const T* last) {
    empty_initialize();
    __STL_TRY {
      insert(begin(), first, last);
    }
    __STL_UNWIND(clear(); put_node(node));
  }
  void range_initialize(const_iterator first, const_iterator last) {
    empty_initialize();
    __STL_TRY {
      insert(begin(), first, last);
    }
    __STL_UNWIND(clear(); put_node(node));
  }
#endif /* __STL_MEMBER_TEMPLATES */


protected:
  link_type node; //只要一个指针,便可表示整个环状双向链表。
  // node指向刻意置于尾端的一个空白节点,满足"前闭后开"


public:
  list() { empty_initialize(); } // 产生一个空链表


  iterator begin() { return (link_type)((*node).next); }
  const_iterator begin() const { return (link_type)((*node).next); }
  iterator end() { return node; }
  const_iterator end() const { return 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 node->next == 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<T, Alloc>& x) { __STD::swap(node, x.node); }
  //在迭代器 positioni 所指空间插入一个节点,内容为 x
  iterator insert(iterator position, const T& x) {
    //使用 create_node 配置并构造一个节点,让它的值为 x
	link_type tmp = create_node(x);
	//调整双向指针,使 tmp 插入进去
    tmp->next = position.node;
    tmp->prev = position.node->prev;
    (link_type(position.node->prev))->next = tmp;
    position.node->prev = tmp;
    return tmp;
  }
  iterator insert(iterator position) { return insert(position, T()); }
#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  void insert(iterator position, InputIterator first, InputIterator last);
#else /* __STL_MEMBER_TEMPLATES */
  void insert(iterator position, const T* first, const T* last);
  void insert(iterator position,
              const_iterator first, const_iterator last);
#endif /* __STL_MEMBER_TEMPLATES */
  void insert(iterator pos, size_type n, const T& x);
  void insert(iterator pos, int n, const T& x) {
    insert(pos, (size_type)n, x);
  }
  void insert(iterator pos, long n, const T& x) {
    insert(pos, (size_type)n, x);
  }


  void push_front(const T& x) { insert(begin(), x); }
  void push_back(const T& x) { insert(end(), x); }
  iterator erase(iterator position) {
    link_type next_node = link_type(position.node->next);
    link_type prev_node = link_type(position.node->prev);
    prev_node->next = next_node;
    next_node->prev = prev_node;
    destroy_node(position.node);
    return iterator(next_node);
  }
  iterator erase(iterator first, iterator last);
  void resize(size_type new_size, const T& x);
  void resize(size_type new_size) { resize(new_size, T()); }
  void clear();


  void pop_front() { erase(begin()); } //移除头节点
  void pop_back() {  //移除尾节点 其实可能直接 erase(--end()); 不过效果一样
    iterator tmp = end();
    erase(--tmp);
  }
  list(size_type n, const T& value) { fill_initialize(n, value); }
  list(int n, const T& value) { fill_initialize(n, value); }
  list(long n, const T& value) { fill_initialize(n, value); }
  explicit list(size_type n) { fill_initialize(n, T()); }


#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  list(InputIterator first, InputIterator last) {
    range_initialize(first, last);
  }


#else /* __STL_MEMBER_TEMPLATES */
  list(const T* first, const T* last) { range_initialize(first, last); }
  list(const_iterator first, const_iterator last) {
    range_initialize(first, last);
  }
#endif /* __STL_MEMBER_TEMPLATES */
  list(const list<T, Alloc>& x) {
    range_initialize(x.begin(), x.end());
  }
  ~list() {
    clear();
    put_node(node);
  }
  list<T, Alloc>& operator=(const list<T, Alloc>& x);


protected:
  //将某连续范围[first, last)的元素迁移到某个特定位置 position 之前
  //非公开接口
  void transfer(iterator position, iterator first, iterator last) {
    if (position != last) { //如果 position == last 那就不用迁移了
      (*(link_type((*last.node).prev))).next = position.node;
      (*(link_type((*first.node).prev))).next = last.node;
      (*(link_type((*position.node).prev))).next = first.node;  
      link_type tmp = link_type((*position.node).prev);
      (*position.node).prev = (*last.node).prev;
      (*last.node).prev = (*first.node).prev; 
      (*first.node).prev = tmp;
    }
  }


public:
  //将 x 接合于 position 所指位置之前。 x 必须不同于 *this --> 这样限制 x 好吗? 不应该提前到编译期提醒客户端吗?我试了下 x 等于 *this,运行没出错
  void splice(iterator position, list& x) {
    if (!x.empty()) 
      transfer(position, x.begin(), x.end());
  }
  //将 i 所指元素接合于 position 所指位置之前。 position 和 i 可指向同一个 list
  // ?? 这里 list &参数有什么用? --> 我感觉没用,有迭代器 i 就够了
  void splice(iterator position, list&, iterator i) {
    iterator j = i;
    ++j;
    if (position == i || position == j) return; //transfer 里有判断 position == j 的情况,没判断 position  == i 的情况,而将自己移到自己前面什么都不用做
    transfer(position, i, j);
  }
  //将 [first, last) 内的所有元素接合于 position 所指位置之前
  // position 和 [first, last) 可指向同一个 list,
  // 但 position 不能位于 [first, last) 之内
  void splice(iterator position, list&, iterator first, iterator last) {
    if (first != last) 
      transfer(position, first, last);
  }
  void remove(const T& value);
  void unique();
  void merge(list& x);
  void reverse();
  void sort();


#ifdef __STL_MEMBER_TEMPLATES
  template <class Predicate> void remove_if(Predicate);
  template <class BinaryPredicate> void unique(BinaryPredicate);
  template <class StrictWeakOrdering> void merge(list&, StrictWeakOrdering);
  template <class StrictWeakOrdering> void sort(StrictWeakOrdering);
#endif /* __STL_MEMBER_TEMPLATES */


  friend bool operator== __STL_NULL_TMPL_ARGS (const list& x, const list& y);
};


template <class T, class Alloc>
inline bool operator==(const list<T,Alloc>& x, const list<T,Alloc>& y) {
  typedef typename list<T,Alloc>::link_type link_type;
  link_type e1 = x.node;
  link_type e2 = y.node;
  link_type n1 = (link_type) e1->next;
  link_type n2 = (link_type) e2->next;
  for ( ; n1 != e1 && n2 != e2 ;
          n1 = (link_type) n1->next, n2 = (link_type) n2->next)
    if (n1->data != n2->data)
      return false;
  return n1 == e1 && n2 == e2;
}


template <class T, class Alloc>
inline bool operator<(const list<T, Alloc>& x, const list<T, Alloc>& y) {
  return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}


#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER


template <class T, class Alloc>
inline void swap(list<T, Alloc>& x, list<T, Alloc>& y) {
  x.swap(y);
}


#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */


#ifdef __STL_MEMBER_TEMPLATES


template <class T, class Alloc> template <class InputIterator>
void list<T, Alloc>::insert(iterator position,
                            InputIterator first, InputIterator last) {
  for ( ; first != last; ++first)
    insert(position, *first);
}


#else /* __STL_MEMBER_TEMPLATES */


template <class T, class Alloc>
void list<T, Alloc>::insert(iterator position, const T* first, const T* last) {
  for ( ; first != last; ++first)
    insert(position, *first);
}


template <class T, class Alloc>
void list<T, Alloc>::insert(iterator position,
                            const_iterator first, const_iterator last) {
  for ( ; first != last; ++first)
    insert(position, *first);
}


#endif /* __STL_MEMBER_TEMPLATES */


template <class T, class Alloc>
void list<T, Alloc>::insert(iterator position, size_type n, const T& x) {
  for ( ; n > 0; --n)
    insert(position, x);
}


template <class T, class Alloc>
list<T,Alloc>::iterator list<T, Alloc>::erase(iterator first, iterator last) {
  while (first != last) erase(first++);
  return last;
}


template <class T, class Alloc>
void list<T, Alloc>::resize(size_type new_size, const T& x)
{
  iterator i = begin();
  size_type len = 0;
  for ( ; i != end() && len < new_size; ++i, ++len)
    ;
  if (len == new_size)
    erase(i, end());
  else                          // i == end()
    insert(end(), new_size - len, x);
}


template <class T, class Alloc> 
void list<T, Alloc>::clear()
{
  link_type cur = (link_type) node->next;
  while (cur != node) { //遍历每一个节点
    link_type tmp = cur;
    cur = (link_type) cur->next; 
    destroy_node(tmp); //析构并释放一个节点
  }
  node->next = node; //恢复空链表时的节点状态
  node->prev = node;
}


template <class T, class Alloc>
list<T, Alloc>& list<T, Alloc>::operator=(const list<T, Alloc>& x) {
  if (this != &x) {
    iterator first1 = begin();
    iterator last1 = end();
    const_iterator first2 = x.begin();
    const_iterator last2 = x.end();
    while (first1 != last1 && first2 != last2) *first1++ = *first2++;
    if (first2 == last2)
      erase(first1, last1);
    else
      insert(last1, first2, last2);
  }
  return *this;
}
//将数值为 value 之所有元素移除
template <class T, class Alloc>
void list<T, Alloc>::remove(const T& value) {
  iterator first = begin();
  iterator last = end();
  while (first != last) {
    iterator next = first;
    ++next;
    if (*first == value) erase(first);
    first = next;
  }
}
//移除连续相同的元素,只保留一个
template <class T, class Alloc>
void list<T, 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 T, class Alloc>
void list<T, Alloc>::merge(list<T, Alloc>& x) {
  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);
}


// reverse() 将 *this 的内容逆向重置
template <class T, class Alloc>
void list<T, Alloc>::reverse() {
  if (node->next == node || link_type(node->next)->next == node) return;
  iterator first = begin();
  ++first;
  while (first != end()) {
    iterator old = first;
    ++first;
    transfer(begin(), old, first);
  }
}    


/* list 不能使用 STL 算法 sort(), 必须使用自己的 sort() 成员函数
 因为 STL 算法 sort() 只接受 RandomAccessItertor 
 ?? STL 算法 sort() 为什么不设计接受 BidirectionalIterator 
 不过我觉得即使 STL 算法 sort() 接受 BidirectionalIterator , 它里面实现也是
 用类似 iter_swap 的方法,这里也要针对链表的特点重新写 sort() 函数
/*
template <class T, class Alloc>
void list<T, Alloc>::sort() {
  //
  if (node->next == node || link_type(node->next)->next == node) return;
  list<T, Alloc> carry;
  list<T, 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_TEMPLATES


template <class T, class Alloc> template <class Predicate>
void list<T, 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 T, class Alloc> template <class BinaryPredicate>
void list<T, Alloc>::unique(BinaryPredicate binary_pred) {
  iterator first = begin();
  iterator last = end()  while (++next != last) {
    if (binary_pred(*first, *next))
      erase(next);
    else
      first = next;
    next = first;
  }
}


template <class T, class Alloc> template <class StrictWeakOrdering>
void list<T, Alloc>::merge(list<T, Alloc>& x, StrictWeakOrdering 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 T, class Alloc> template <class StrictWeakOrdering>
void list<T, Alloc>::sort(StrictWeakOrdering comp) {
  if (node->next == node || link_type(node->next)->next == node) return;
  list<T, Alloc> carry;
  list<T, 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]);
}


#endif /* __STL_MEMBER_TEMPLATES */


#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma reset woff 1174
#endif


__STL_END_NAMESPACE 


#endif /* __SGI_STL_INTERNAL_LIST_H */


// Local Variables:
// mode:C++
// End: