当前位置:首页 » 《关注互联网》 » 正文

[C/C++]详解STL容器3--list的功能和模拟实现(迭代器失效问题)_RMA515T的博客

17 人参与  2022年01月13日 10:18  分类 : 《关注互联网》  评论

点击全文阅读


本文介绍了list的常用接口的使用,并对其进行了模拟实现,包括list迭代器的实现。

目录

一、list的介绍

二、list的常用接口的使用

1. list的构造

2. list iterator的使用

3.list capacity的使用

4.list element access

5.list modifiers

6. list的迭代器失效

三、list与vector的对比

四、list的模拟实现


一、list的介绍

list 容器,又称双向链表容器,即该容器的底层是以双向链表的形式实现的。这意味着,list 容器中的元素可以分散存储在内存空间里,而不是必须存储在一整块连续的内存空间中。结构如图。

 list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代

list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高效。

 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好。最大的缺陷是不支持任意位置的随机访问,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间;list还需要一些额外的空间,以保存每个节点的相关联信息。

二、list的常用接口的使用

1. list的构造

构造函数( (constructor))接口说明
list()构造空的list
list (size_type n, const value_type& val = value_type())构造的list中包含n个值为val的元素
list (const list& x)拷贝构造函数
list (InputIterator first, InputIterator last)用[first, last)区间中的元素构造list
#include <iostream>
#include <list>

int main ()
{
    std::list<int> a; // 构造空的a
    std::list<int> b (4,1); // b中放4个值为100的元素

    std::list<int> c (b.begin(), b.end()); // 用b的[begin(), end())左闭右开的区间构造c

    std::list<int> d (c); // 用c拷贝构造d

    // 以数组为迭代器区间构造e
    int array[] = {16,2,77,29};
    std::list<int> e (array, array + sizeof(array) / sizeof(int) );

    // 用迭代器方式打印e中的元素
    for(std::list<int>::iterator it = e.begin(); it != e.end(); it++)
        std::cout << *it << " ";
    std::cout<<endl;

    // C++11范围for的方式遍历
    for(auto& e : e)
        std::cout<< e << " ";
    std::cout<<endl;

    return 0;
}

2. list iterator的使用

函数声明接口说明
begin + end返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器
rbegin + rend返回第一个元素的reverse_iterator,即end位置,返回最后一个元素下一个位置的reverse_iterator,即begin位置

begin与end为正向迭代器,对迭代器执行++操作,迭代器向后移动。
rbegin(end)与rend(begin)为反向迭代器,对迭代器执行++操作,迭代器向前移动。

 

#include <iostream>
using namespace std;
#include <list>

void print_list(const list<int>& l)
{
    // 注意这里调用的是list的 begin() const,返回list的const_iterator对象
    for (list<int>::const_iterator it = l.begin(); it != l.end(); ++it)
    {
        cout << *it << " ";
        // *it = 10; 编译不通过
    }
    cout << endl;
}

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    list<int> l(array, array + sizeof(array) / sizeof(array[0]));

    // 使用正向迭代器正向list中的元素
    for (list<int>::iterator it = l.begin(); it != l.end(); ++it)
        cout << *it << " ";
    cout << endl;

    // 使用反向迭代器逆向打印list中的元素
    for (list<int>::reverse_iterator it = l.rbegin(); it != l.rend(); ++it)
        cout << *it << " ";
    cout << endl;

    return 0;
}

3.list capacity的使用

函数声明接口说明
empty检测list是否为空,是返回true,否则返回false
size返回list中有效节点的个数

4.list element access

函数声明接口说明
front返回list的第一个节点中值的引用
back返回list的最后一个节点中值的引用

5.list modifiers

函数声明接口说明
push_front在list首元素前插入值为val的元素
pop_front删除list中第一个元素
push_back在list尾部插入值为val的元素
pop_back删除list中最后一个元素
insert在list position 位置中插入值为val的元素
erase删除list position位置的元素
swap交换两个list中的元素
clear清空list中的有效元素

6. list的迭代器失效

此处可将迭代器暂时理解成类似于指针,迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致list的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响。

三、list与vector的对比

vectorlist



动态顺序表,一段连续空间带头结点的双向循环链表


访
支持随机访问,访问某个元素效率O(1)不支持随机访问,访问某个元素效率O(N)




任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(N),插入时有可能需要增容,增容:开辟新空间,拷贝元素,释放旧空间,导致效率更低




底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低


原生态指针对原生态指针(节点指针)进行封装




在插入元素时,要给所有的迭代器重新赋值,因为插入元素有可能会导致重新扩容,致使原来迭代器失效,删除时,当前迭代器需要重新赋值否则会失效插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响
使


需要高效存储,支持随机访问,不关心插入删除效率大量插入和删除操作,不关心随机访问

四、list的模拟实现

 list的模拟实现十分有趣,这里需要注意,list本身和list的节点是不同的结构,所以需要分开设计。成员都是只需浅拷贝,所以拷贝构造,析构 ,重载 = 都可以使用默认。

list iterator也需要单独设计,因为原生指针已经无法满足迭代器需求,所以需要封装,让它像一个指针一样完成访问操作。

通过template <class T, class Ref, class Ptr>区别T&,*T。

#include <iostream>
#include <list>
#include <assert.h>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

namespace Zht
{
  template <class T>
  
  struct _list_node     //list本身和list的节点是不同的结构,所以需要分开设计,这里是list节点的结构
  {
      T val;              //数据
      _list_node<T>* _next;       //下一个节点指针
      _list_node<T>* _prev;       //上一个
      
      _list_node(const T& val = T())      //构造节点
        :val(val)                         //传的参
        ,_prev(nullptr)
        ,_next(nullptr)
      {
          
      }
  };

  template <class T, class Ref, class Ptr>
  struct _list_iterator 
  {
    typedef _list_node<T> node;
    typedef _list_iterator<T, Ref, Ptr> self;

    node* _pnode;      //迭代器本质上是指针

    _list_iterator(node* pnode)     //构造函数
      :_pnode(pnode)
    {
    }

    //这里,成员都是只需浅拷贝,所以拷贝构造,析构 ,重载 = 都可以使用默认
   
    Ref operator*()       //重载*,通过Ref灵活的调整const和普通。
    {
      return _pnode->val;
    }

    bool operator!=(const self& s) const 
    {
      return _pnode != s._pnode;
    }

    bool operator==(const self& s) const 
    {
      return _pnode == s._pnode;
    }

    self& operator++()            //++就是指向下一个节点
    {
      _pnode = _pnode->_next;

      return *this;
    }

    self operator++(int)          //C++规定后缀调用需要有一个int型参数作为区分前缀与后缀调用的区别
    {
      self tmp (*this);
      ++*this;
      return tmp;                 //*this++后++
    }

    self& operator--()
    {
      _pnode = _pnode->_prev;

      return *this;
    }

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

    Ptr operator->()
    {
      return &(operator*());      
    }
  };

  template <class T>
  class list
  {
      typedef _list_node<T> node;
  public:
      typedef _list_iterator<T, T&, T*> iterator;
      typedef _list_iterator<T,const T&, const T*> const_iterator;


      list()      //构造函数,构造哨兵位
      {
          _head = new node;           //开一个节点
          _head->_next = _head;       //初始化节点
          _head->_prev = _head;
      }

      template <class Iterator>
      list(Iterator first, Iterator last)
      {
        _head = new node;
        _head->_next = _head;
        _head->_prev = _head;

        while(first != last)
        {
          push_back(*first);
          first++;
        }
      }

      list(const list<T>& It)
      {
        _head = new node;                   //构造哨兵节点
        _head->_next = _head;     
        _head->_prev = _head;

        for(const auto& e : It)             //逐个尾插
        {
          push_back(e);
        }
      }

      list<T>& operator=(list<T> It)
      {
        swap(_head, It._head);

        return *this;
      }

      ~list()
      {
        clear();
        delete _head;
        _head = nullptr;
      }

      iterator begin()
      {
        return iterator(_head->_next);
      }

      const_iterator begin() const            //调用const的迭代器,返回一个用_head->next构造的迭代器对象
      {
        return const_iterator(_head->_next); 
      }

      iterator end()                          
      {
        return iterator(_head);
      }

      const_iterator end() const 
      {
        return const_iterator(_head);
      }

      void push_back(const T& x)        //只有哨兵位的也可以通用
      {
         /* node* newnode = new node(x);    //创建新节点
          node* tail = _head->_prev;      //当前的最后一个节点

          tail->_next = newnode;
          newnode->_next = _head;
          newnode->_prev = tail;
          _head->_prev = newnode;*/

        insert(iterator(end()), x);     //前一个就是尾
      }
      
      void push_front(const T& x)
      {
        insert(iterator(begin),x);
      }

      void pop_back()
      {
        erase(iterator(--end()));
      }

      void pop_front()
      {
        erase(iterator(begin()));
      }
      
      iterator insert(iterator pos, const T& val)       //pos位置前插入
      {
        node* newnode = new node(val);
        node* tail = pos._pnode;

        newnode->_next = tail;
        newnode->_prev = tail->_prev;
        newnode->_prev->_next = newnode;              //还要让前一个指向自己
        pos._pnode->_prev = newnode;

        return iterator(newnode);                     //需要返回迭代器;
      }

      iterator erase(iterator pos)    //删除pos位置        
      {
        assert(pos._pnode);
        assert(pos != end());

        node* tail = pos._pnode;
        node* ret = tail->_next;
        tail->_prev->_next = tail->_next;
        tail->_next->_prev = tail->_prev;

        delete tail;

        return iterator(ret);       //返回下一个
      }

      bool empty()
      {
        return begin() == end();
      }

      size_t size()
      {
        size_t sz = 0;
        iterator it = begin();

        while(it != end())
        {
          sz++;
          it++;
        }

        return sz;
      }

      void clear()
      {
        iterator it = begin();

        while(it != end())
        {
          erase(it);
          it++;
        }
      }

      

  private:
      node* _head;
  };
  
  void PrintList(const list<int>& It)
  {
    list<int>::const_iterator it = It.begin();

    while(it != It.end())
    {
      cout << *it <<endl;
      ++it;
    }
    
    cout << endl;
  }

  void test1()
  {
    list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);

		list<int>::iterator it = lt.begin();
		while (it != lt.end())
		{
			*it += 1;
			cout << *it << " ";
			++it;
		}
		cout << endl;

		for (auto e : lt)
		{
			cout << e << " ";
		}
		cout << endl;

		PrintList(lt);
  }
}

 


点击全文阅读


本文链接:http://zhangshiyu.com/post/33155.html

迭代  节点  元素  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1