序列式容器——list

   相比较vector的连续线性空间,list就显得复杂很多,它的好处是每次插入或者删除一个元素,就配置或者释放一个元素空间。因此,list对于空间运用有绝对的精准,一点也不浪费。而且对于任何位置的元素插入和元素移除,list永远是常数。

    list本身和list节点是不同的结构,需要分开设计。

    下面是list节点的结构:

template<typename T>
struct __list_node{
    typedef void* void_pointer;
    void_pointer prev; //类型为void*,其实可以设置成__list_node<T>*
    void_pointer next;
    T data;
}

    list有一个重要的性质:插入操作(insert)和接合操作(splice)都不会造成原有的list迭代器失效。这再vector是不成立的,因为vector的插入操作可能造成原有的迭代器全部失效。甚至list的元素删除操作(erase)也只有“指向被删除元素”的那个迭代器失效,其它迭代器不会受任何影响。

    list迭代器的设计如下:

template <typename T, typename Ref, typename Ptr>
struct __list_iterator{
    typedef __list_iterator<T, T&, T*> 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 __link_node<T>* link_type;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;

    link_type node;//迭代器内部当然要有一个普通指针,指向list的节点

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

    bool operator==(const self& x) const {return node == x.node;}
    reference operator*() const {return (*node).data;}
    //以下是迭代器的成员存取,运算子的标准做法
    pointer operator->() const {return &(operator*());}

    //对迭代器执行加++操作
    self& operator++(){//前置++,注意这里的返回值使用引用,不使用引用的时候,会创建临时变量返回
        node = (link_type)((*node).next);
        return *this;
    }
    self operator(int){//这就是为什么前置的++速度要快,因为后置的++需要临时变量
        self temp = *this;
        ++*this;
        return temp;
    }
}

    SGI list不仅是一个双向链表,而且还是一个环状双向链表。所以只需要一个指针,便可以完整遍历整个链表:     

template<typename T, class Alloc = alloc>//缺省使用alloc为分配器
class list{
protected:
    typedef __list_node<T> list_node;
public:
    typedef list_node* link_type;
protected:
    link_type node;//只需一个指针就可以变量整个链表
}

    如果让指针node指向刻意置于尾端的一个空白节点,node便能符合STL对于前闭后开区间的要求。

    List提供的元素操作有:

       push_front(const T& x); //在链表头插入一个节点

       pop_front();//移除头节点

       push_back(const T& x);//在链表尾插入节点

       pop_back();//移除尾节点

       erase(iterator position)//移除迭代器position所指的节点

       clear()//清楚所有节点(整个链表)

       reverse()//将链表翻转过来

       sort()//这里的sort函数不是算法中的sort函数,而是list类中的成员函数,默认是升序排序

      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值