《STL原始碼剖析》-- stl_list.h

凝霜發表於2011-07-29
// Filename:    stl_list.h

// Comment By:  凝霜
// E-mail:      mdl2009@vip.qq.com
// Blog:        http://blog.csdn.net/mdl13412

/*
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Hewlett-Packard Company makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 *
 * Copyright (c) 1996,1997
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 */

/* NOTE: This is an internal header file, included by other STL headers.
 *   You should not attempt to use it directly.
 */

#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結點, 提供雙向訪問能力
////////////////////////////////////////////////////////////////////////////////
//  --------           --------           --------           --------
//  | next |---------->| next |---------->| next |---------->| next |
//  --------           --------           --------           --------
//  | prev |<----------| prev |<----------| prev |<----------| prev |
//  --------           --------           --------           --------
//  | data |           | data |           | data |           | data |
//  --------           --------           --------           --------
////////////////////////////////////////////////////////////////////////////////

template <class T>
struct __list_node
{
  typedef void* void_pointer;
  void_pointer next;
  void_pointer prev;
  T data;
};

// 至於為什麼不使用預設引數, 這個是因為有一些編譯器不能提供推導能力,
// 而作者又不想維護兩份程式碼, 故不使用預設引數
template<class T, class Ref, class Ptr>
struct __list_iterator
{
  // 標記為'STL標準強制要求'的typedefs用於提供iterator_traits<I>支援
  typedef __list_iterator<T, T&, T*>             iterator;   // STL標準強制要求
  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;                                 // STL標準強制要求
  typedef Ptr pointer;                                  // STL標準強制要求
  typedef Ref reference;                                // STL標準強制要求
  typedef __list_node<T>* link_type;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;                    // STL標準強制要求

  // 這個是迭代器實際管理的資源指標
  link_type node;

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

  // 在STL演算法中需要迭代器提供支援
  bool operator==(const self& x) const { return node == x.node; }
  bool operator!=(const self& x) const { return node != x.node; }

  // 過載operator *, 返回實際維護的資料
  reference operator*() const { return (*node).data; }

#ifndef __SGI_STL_NO_ARROW_OPERATOR
  // 如果支援'->'則過載之
  // 解釋一下為什麼要返回地址
  // class A
  // {
  // public:
  //    // ...
  //    void fun();
  //    // ...
  // }
  // __list_iterator<A, A&, A*> iter(new A)
  // iter->fun();
  // 這就相當於呼叫(iter.operator())->fun();
  // 經過過載使其行為和原生指標一致
  pointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */

  // 字首自加
  self& operator++()
  {
    node = (link_type)((*node).next);
    return *this;
  }

  // 字尾自加, 需要先產生自身的一個副本, 然會再對自身操作, 最後返回副本
  self operator++(int)
  {
    self tmp = *this;
    ++*this;
    return tmp;
  }

  self& operator--()
  {
    node = (link_type)((*node).prev);
    return *this;
  }

  self operator--(int)
  {
    self tmp = *this;
    --*this;
    return tmp;
  }
};

// 如果編譯器支援模板類偏特化那麼就不需要提供以下traits函式
// 直接使用<stl_iterator.h>中的
// template <class Iterator>
// struct iterator_traits
#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 */

////////////////////////////////////////////////////////////////////////////////
// 連結串列本身成環, 且是雙向連結串列, 這樣計算begin()和end()是常數時間
////////////////////////////////////////////////////////////////////////////////
//       end()              頭結點             begin()
//         ↓                  ↓                  ↓
//      --------           --------           --------           --------
// ---->| next |---------->| next |---------->| next |---------->| next |------
// |    --------           --------           --------           --------     |
// |  --| prev |<----------| prev |<----------| prev |<----------| prev |<--| |
// |  | --------           --------           --------           --------   | |
// |  | | data |           | data |           | data |           | data |   | |
// |  | --------           --------           --------           --------   | |
// |  |                                                                     | |
// |  | --------           --------           --------           --------   | |
// ---|-| next |<----------| next |<----------| next |<----------| next |<--|--
//    | --------           --------           --------           --------   |
//    ->| prev |---------->| prev |---------->| prev |---------->| prev |----
//      --------           --------           --------           --------
//      | data |           | data |           | data |           | data |
//      --------           --------           --------           --------
////////////////////////////////////////////////////////////////////////////////

// 預設allocator為alloc, 其具體使用版本請參照<stl_alloc.h>
template <class T, class Alloc = alloc>
class list
{
protected:
  typedef void* void_pointer;
  typedef __list_node<T> list_node;

  // 這個提供STL標準的allocator介面
  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:
  // 分配一個新結點, 注意這裡並不進行構造,
  // 構造交給全域性的construct, 見<stl_stl_uninitialized.h>
  link_type get_node() { return list_node_allocator::allocate(); }

  // 釋放指定結點, 不進行析構, 析構交給全域性的destroy,
  // 見<stl_stl_uninitialized.h>
  void put_node(link_type p) { list_node_allocator::deallocate(p); }

  // 建立結點, 首先分配記憶體, 然後進行構造
  // 注: commit or rollback
  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->next = node;
    node->prev = node;
  }

  // 建立值為value共n個結點的連結串列
  // 注: commit or rollback
  void fill_initialize(size_type n, const T& value)
  {
    empty_initialize();
    __STL_TRY {
      // 此處插入操作時間複雜度O(1)
      insert(begin(), n, value);
    }
    __STL_UNWIND(clear(); put_node(node));
  }

// 以一個區間初始化連結串列
// 注: commit or rollback
#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;

public:
  list() { empty_initialize(); }

  iterator begin() { return (link_type)((*node).next); }
  const_iterator begin() const { return (link_type)((*node).next); }

  // 連結串列成環, 當指所以頭節點也就是end
  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; }

  // 使用全域性函式distance()進行計算, 時間複雜度O(n)
  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); }

////////////////////////////////////////////////////////////////////////////////
// 在指定位置插入元素
////////////////////////////////////////////////////////////////////////////////
//       insert(iterator position, const T& x)
//                       ↓
//                 create_node(x)
//                 p = get_node();-------->list_node_allocator::allocate();
//                 construct(&p->data, x);
//                       ↓
//            tmp->next = position.node;
//            tmp->prev = position.node->prev;
//            (link_type(position.node->prev))->next = tmp;
//            position.node->prev = tmp;
////////////////////////////////////////////////////////////////////////////////

  iterator insert(iterator position, const T& x)
  {
    link_type tmp = create_node(x);
    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 */

  // 指定位置插入n個值為x的元素, 詳細解析見實現部分
  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()
  {
    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()
  {
    // 釋放所有結點  // 使用全域性函式distance()進行計算, 時間複雜度O(n)
  size_type size() const
  {
    size_type result = 0;
    distance(begin(), end(), result);
    return result;
  }
    clear();
    // 釋放頭結點
    put_node(node);
  }

  list<T, Alloc>& operator=(const list<T, Alloc>& x);

protected:

////////////////////////////////////////////////////////////////////////////////
// 將[first, last)區間插入到position
// 如果last == position, 則相當於連結串列不變化, 不進行操作
////////////////////////////////////////////////////////////////////////////////
// 初始狀態
//                   first                             last
//                     ↓                                 ↓
//      --------   --------   --------     --------   --------   --------
//      | next |-->| next |-->| next |     | next |-->| next |-->| next |
//  ... --------   --------   -------- ... --------   --------   -------- ...
//      | prev |<--| prev |<--| prev |     | prev |<--| prev |<--| prev |
//      --------   --------   --------     --------   --------   --------
//
//                           position
//                               ↓
//      --------   --------   --------   --------   --------   --------
//      | next |-->| next |-->| next |-->| next |-->| next |-->| next |
//  ... --------   --------   --------   --------   --------   -------- ...
//      | prev |<--| prev |<--| prev |<--| prev |<--| prev |<--| prev |
//      --------   --------   --------   --------   --------   --------
//
// 操作完成後狀態
//                           first
//                             |
//               --------------|--------------------------------------
//               | ------------|------------------------------------ |   last
//               | |           ↓                                   | |     ↓
//      -------- | |        --------   --------     --------       | |  --------   --------
//      | next |-- |  ----->| next |-->| next |     | next |-----  | -->| next |-->| next |
//  ... --------   |  |     --------   -------- ... --------    |  |    --------   -------- ...
//      | prev |<---  |  ---| prev |<--| prev |     | prev |<-- |  -----| prev |<--| prev |
//      --------      |  |  --------   --------     --------  | |       --------   --------
//                    |  |                                    | |
//                    |  ------                               | |
//                    ------- |  ------------------------------ |
//                          | |  |                              |
//                          | |  |  -----------------------------
//                          | |  |  |
//                          | |  |  |  position
//                          | |  |  |     ↓
//      --------   -------- | |  |  |  --------   --------   --------   --------
//      | next |-->| next |-- |  |  -->| next |-->| next |-->| next |-->| next |
//  ... --------   --------   |  |     --------   --------   --------   -------- ...
//      | prev |<--| prev |<---  ------| prev |<--| prev |<--| prev |<--| prev |
//      --------   --------            --------   --------   --------   --------
////////////////////////////////////////////////////////////////////////////////
  void transfer(iterator position, iterator first, iterator last)
  {
    if (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之前
  void splice(iterator position, list& x)
  {
    if (!x.empty())
      transfer(position, x.begin(), x.end());
  }

  // 將連結串列中i指向的內容移動到position之前
  void splice(iterator position, list&, iterator i)
  {
    iterator j = i;
    ++j;
    if (position == i || position == j) return;
    transfer(position, i, j);
  }

  // 將[first, last}元素移動到position之前
  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());
}

// 如果編譯器支援模板函式特化優先順序
// 那麼將全域性的swap實現為使用list私有的swap以提高效率
#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 */

// 將[first, last)區間插入到position之前
#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 */

// 在position前插入n個值為x的元素
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);
}

// 擦除[first, last)間的結點
template <class T, class Alloc>
list<T,Alloc>::iterator list<T, Alloc>::erase(iterator first, iterator last)
{
  while (first != last) erase(first++);
  return last;
}

// 重新設定容量大小
// 如果當前容量小於新容量, 則新增加值為x的元素, 使容量增加至新指定大小
// 如果當前容量大於新容量, 則析構出來的元素
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;
}

// 連結串列賦值操作
// 如果當前容器元素少於x容器, 則析構多餘元素,
// 否則將呼叫insert插入x中剩餘的元素
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;
}

// 移除特定值的所有結點
// 時間複雜度O(n)
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;
  }
}

// 移除容器內所有的相鄰的重複結點
// 時間複雜度O(n)
// 使用者自定義資料型別需要提供operator ==()過載
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;
  }
}

// 假設當前容器和x都已序, 保證兩容器合併後仍然有序
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);
}

// 將連結串列倒置
// 其演算法核心是歷遍連結串列, 每次取出一個結點, 並插入到連結串列起始點
// 歷遍完成後連結串列滿足倒置
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);
  }
}

// 按照升序排序
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();
  if (first == last) return;
  iterator next = first;
  while (++next != last) {
    if (binary_pred(*first, *next))
      erase(next);
    else
      first = next;
    next = first;
  }
}

// 假設當前容器和x均已序, 將x合併到當前容器中, 並保證在comp仿函式
// 判定下仍然有序
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);
}

// 根據仿函式comp據定如何排序
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:

相關文章