STL学习之LIST

STL源码剖析里面对LIST讲解的很透彻。

首先要明白的是在SGI STL中给出的LIST是一个循环双向链表,即用一个头指针便能够遍历从头至尾的元素。

部分源码:

template<class T ,class Alloc=alloc>
class List{
  publc:
    typedef _list_node<T> list_node;
  public:
    typedef list_node* link_type;
 
  protected:
     link_type node;
 .......
};

仅仅一个node便能够简单的实现一下函数:

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

   iterator end(){return (link_type)((*node).pref);}

   iterator empty(){return node->next==node;}等


List由于是一个链式结构的容器,故而需要自己定义专门的迭代器:

template<class T,class Ref,class Ptr><pre name="code" class="cpp">

struct _list_iterator{  
               typedef _list_iterator<T,T&,T*> iterator; 
               typedef _list_iterator<T,Ref,Ptr> self;   
               typedef _list_iterator<T>* link_type; 
         typedef size_t size_type;    
         link_type node; 
               _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;}
                 ...... 

              };

List STL中提供了一个内部函数transfer(iterator position,iterator first,iterator last )的操作将[first,last)内的所有元素移动到position之前。

void transfer(iterator position,iterator first,iterator last){
   if(position!=last)
   {
     //迁移操作,此处图片显示更明朗故而略去
   }

有了transfer这个有用的函数,List的很多功能可以很轻松的实现了如:

void reverse()
{
   if(node==node->next||link_type(node->next)->next==node)//此处判断其size是否为0或1也可以用size()但是效率低
   return;
   
   iterator first=begin();
  while(first!=end())
  {
   iterator old =first;
   ++first;
    transfer(begin(),old,first);
   }

}

List每个节点的生成和销毁都是直接向空间配置器取放的,故而对内存很精确,可以达到节省的目的。且由于其是链式结构故而插入等操作不会对原有的迭代器造成影响。



你可能感兴趣的:(C++,链表,STL)