0


【深入探索 C++ STL 容器 list】 —— 编程世界的万能胶,数据结构中的百变精灵

** STL系列学习参考:**

STL 数据结构与算法__Zwy@的博客-CSDN博客

各位于晏,亦菲们,请点赞关注!

我的个人主页:

_Zwy@-CSDN博客


1、认识标准库中的list

list的参考文档:

cplusplus.com/reference/list/list/?kw=listhttps://cplusplus.com/reference/list/list/?kw=list**头文件为<list>**

list 成员变量

list是C++标准库提供的类模板,本质上是一个双向带头循环链表.

结构如下图所示:

2、list的的常用接口

2.1、Construct 构造函数

2.1.1、list()

默认构造,构造空的list

  1. list<int> mylist1;
  2. list<string> mylist2;
  3. //list中的元素类型为 vector<int>
  4. list<vector<int>> mylist3;

** 默认构造的list元素个数都是0.**

2.1.2、 list (size_type n, const value_type& val)

构造的list中包含n个值为val的元素

  1. //使用n个value构造
  2. list<int> mylist1(10, 5);
  3. list<string> mylist2(3,"hellolist");
  4. //list中的元素类型为 vector<int>
  5. // 第二个参数是vector的initializer list构造
  6. list<vector<int>> mylist3(5,{1,2,3,4,5});

其中mylist3有5个元素,每个元素是size为5的vector.

2.1.3、list (const list& x)(重点)

拷贝构造

  1. //使用n个value构造
  2. list<int> mylist1(10, 5);
  3. list<string> mylist2(3,"hellolist");
  4. //list中的元素类型为 vector<int>
  5. // 第二个参数是vector的initializer list构造
  6. list<vector<int>> mylist3(5,{1,2,3,4,5});
  7. //拷贝构造
  8. list<int> copy1(mylist1);
  9. list<string> copy2(mylist2);
  10. list<vector<int>> copy3(mylist3);

拷贝构造时要注意,拷贝构造对象和被拷贝对象的实例化类型要相同,否则无法构造。

2.1.4、list (InputIterator first, InputIterator last)

迭代器区间构造

  1. //迭代器区间构造
  2. vector<int> v{ 1,2,3,4,5 };
  3. //利用vector的整个区间构造
  4. list<int> listint(v.begin(), v.end());
  5. string s("hellolist");
  6. //使用string的部分区间构造
  7. list<char> listchar(s.begin() + 1, s.end() - 2);
  8. //使用vector<vector<int>> 的迭代器区间
  9. vector<vector<int>> vv(10, { 1,3,5,7,9 });
  10. list<vector<int>> listv(vv.begin() + 2, vv.end() - 3);

使用迭代器区间构造,也需要保证类型匹配!

2.1.5、list的initializer list 构造

  1. //list的initializer list 构造
  2. list<int> list_int{ 1,2,3,4,5 };
  3. list<string> list_str{ "hellolist","string","vector","list" };
  4. //list的initializer list 构造中嵌套了vector的initializer list 构造
  5. list<vector<int>> list_v{ {1,2,3},{3,4,5},{4,5,6} };

list 同样支持C++11提出的initializer list 构造。

2.2、list iterator****(重点)

此处,大家可暂时将迭代器iterator理解成一个指针,该指针指向list中的某个节点。

list的迭代器iterator只支持++和--等自增自减操作,不支持+和-。

2.2.1、begin()+end()

返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器

2.2.2、rbegin()+rend()

*返回第一个元素的*reverse_iterator,end()*位置返回最后一个元素下一个位****reverse_iterator,begin()*位置**

** begin与end为正向迭代器,对迭代器执行++操作,迭代器向后移动 **

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


2.2.3、迭代器遍历

正向迭代器遍历:

  1. list<string> list_s{ "apple","banana","orange","grape","mango","strawberry"};
  2. list<string>::iterator it = list_s.begin();
  3. while (it != list_s.end())
  4. {
  5. //迭代器支持解引用
  6. cout << *it << endl;
  7. ++it;
  8. }

输出:

反向迭代器遍历:

  1. list<string> list_s{ "apple","banana","orange","grape","mango","strawberry"};
  2. list<string>::reverse_iterator it = list_s.rbegin();
  3. while (it != list_s.rend())
  4. {
  5. //迭代器支持解引用
  6. cout << *it << endl;
  7. ++it;
  8. }

输出:

2.3、Capacity 容量

2.3.1、empty()

**检查list是否为空,为空返回true,否则返回false **** **

  1. list<int> list_int;
  2. if (list_int.empty())
  3. cout << "list_int为空" << endl;
  4. else
  5. cout << "list_int不为空" << endl;
  6. list<string> list_str{ 2,"hellolist" };
  7. if (list_str.empty())
  8. cout << "list_str为空" << endl;
  9. else
  10. cout << "list_str不为空" << endl;

输出:

2.3.2、size()

返回list当前的有效节点个数

  1. list<int> myints{ 1,2,3,4,5 };
  2. cout << "myints size:" << myints.size() << endl;
  3. list<char> mychars{ 'a','b','c','d','e','f' };
  4. cout << "mychars size:" << mychars.size() << endl;
  5. list<string> mystrs{ "apple","banana","grape","strawberry"};
  6. cout << "mystrs size:" << mystrs.size() << endl;

输出:

**2.4、Element access **

list 元素访问

2.4.1、front()

返回list的第一个节点中值的引用,如果list中的元素被const修饰,那么就返回const 引用.

  1. list<int> myints{ 1,2,3,4,5 };
  2. cout << "myints.front() is: " << myints.front() << endl;
  3. myints.front() -= 10;
  4. cout << "Now myints.front() is: " << myints.front() << endl;

输出:

2.4.2、back()

返回list的最后一个节点中值的引用,如果list中的元素被const修饰,那么同样返回const 引用.

  1. list<string> mystrs{ "string","vector","linux","windows"};
  2. cout << "mystrs.back() is: " << mystrs.back() << endl;
  3. mystrs.back().append("WINDOWS");
  4. cout << "Now mystrs.back() is: " << mystrs.back() << endl;

输出:

2.4.3、****const_reference

返回const引用的情况

  1. const list<int> c_list{ 1,2,3,4,5 };
  2. //list中元素被const修饰,front和back返回const引用不能修改
  3. //c_list.front() += 10;
  4. //c_list.back() -= 10;

2.5、list modifiers 增删查改

list有关增删查改的接口很多,我们只挑重点的来讲!

2.5.1、push_front()

在list首元素前插入值为val的元素,即头插

2.5.2、push_back()

在list尾部插入值为val的元素,即尾插

  1. void Test_listpush()
  2. {
  3. vector<int> v{ 1,2,3,4,5 };
  4. list<int> mylist(v.begin(), v.end());
  5. cout << "插入前:" << endl;
  6. for (auto e : mylist)
  7. {
  8. cout << e << " ";
  9. }
  10. cout << endl;
  11. mylist.push_front(0);
  12. mylist.push_back(6);
  13. cout << "插入后:" << endl;
  14. for (auto e : mylist)
  15. {
  16. cout << e << " ";
  17. }
  18. cout << endl;
  19. }

输出:

2.5.3、pop_front()

删除list中第一个元素

2.5.4、pop_back()

删除list中最后一个元素

  1. void Test_listpop()
  2. {
  3. list<char> mylist{ 'a','b','c','d','e' };
  4. cout << "删除前:" << endl;
  5. for (auto e : mylist)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. mylist.pop_front();
  11. mylist.pop_back();
  12. cout << "删除后:" << endl;
  13. for (auto e : mylist)
  14. {
  15. cout << e << " ";
  16. }
  17. cout << endl;
  18. }

输出:

2.4.5、insert()

在list position 位置前插入值为val的元素,其中position是一个迭代器

如果成功插入,则返回新插入的第一个元素的迭代器

  1. void Test_listinsert()
  2. {
  3. list<string> mylist{ "Java","C++","PHP","Python","C" };
  4. cout << "insert前:" << endl;
  5. for (auto e : mylist)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. //在position位置前插入val
  11. mylist.insert(mylist.begin(), "bash");
  12. //在position位置前 插入 n个val
  13. mylist.insert(++mylist.begin(), 3, "C#");
  14. //在position位置前 插入一段迭代器区间
  15. vector<string> v{ "Go","Rust","SQL" };
  16. mylist.insert(mylist.end(), v.begin(), v.end());
  17. cout << "insert 后:" << endl;
  18. for (auto e : mylist)
  19. {
  20. cout << e << " ";
  21. }
  22. cout << endl;
  23. }

输出:

2.5.6、erase()

删除list position位置的元素,其中position同样是一个迭代器。返回值是一个迭代器,指向被删除元素之后的那个元素。如果被删除的元素是list中的最后一个元素,那么返回end()

** erase的返回值非常重要,有关list的迭代器失效问题 !!!**

  1. void Test_erase()
  2. {
  3. list<string> mylist{ "Java","C++","PHP","Python","C","bash","Go","Rust","SQL"};
  4. cout << "erase前:" << endl;
  5. for (auto e : mylist)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. //删除position位置的元素
  11. mylist.erase(mylist.begin());
  12. mylist.erase(--mylist.end());
  13. //删除一段迭代器区间[firsr,last) 左闭右开
  14. mylist.erase(++mylist.begin(), --mylist.end());
  15. cout << "erase后:" << endl;
  16. for (auto e : mylist)
  17. {
  18. cout << e << " ";
  19. }
  20. cout << endl;
  21. }

输出:

2.5.7、swap()

交换两个类型相同的list中的元素

  1. void printlist(list<int> l)
  2. {
  3. for (auto e : l)
  4. {
  5. cout << e<< " ";
  6. }
  7. cout << endl;
  8. }
  9. void Test_swap()
  10. {
  11. list<int> list1{ 1,3,5,7,9 };
  12. list<int> list2{ 2,4,6,8,10 };
  13. cout << "swap前:" << endl;
  14. printlist(list1);
  15. printlist(list2);
  16. list1.swap(list2);
  17. cout << "swap后:" << endl;
  18. printlist(list1);
  19. printlist(list2);
  20. }

输出:

2.5.8、clear()

清除list中的所有元素

  1. void Test_clear()
  2. {
  3. list<string> list_str{"clear","swap","push_back","insert","erase","pop_front"};
  4. cout << "clear前:" << endl;
  5. for (auto e : list_str)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. list_str.clear();
  11. cout << "clear后:" << endl;
  12. for (auto e : list_str)
  13. {
  14. cout << e << "";
  15. }
  16. }

输出:

2.5.9、resize()

如果n小于当前list的size,size减少到前n个元素,并删除超出的元素。

如果n大于当前容器的size,则在末尾插入所需的元素,如果指定了val,则将新元素初始化为val的,否则将其进行值初始化。

n<list当前size的情况:

  1. void Test_resize()
  2. {
  3. list<int> list_int{ 1,2,3,4,5 };
  4. cout << "resize前:" << endl;
  5. for (auto e : list_int)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. list_int.resize(3);
  11. cout << "resize前:" << endl;
  12. for (auto e : list_int)
  13. {
  14. cout << e << " ";
  15. }
  16. }

输出:

n>list 当前size的情况:

  1. void Test_resize()
  2. {
  3. list<int> list_int{ 1,2,3,4,5 };
  4. cout << "resize前:" << endl;
  5. for (auto e : list_int)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. //不给value的情况 初始化默认值
  11. list_int.resize(10);
  12. cout << "resize前:" << endl;
  13. for (auto e : list_int)
  14. {
  15. cout << e << " ";
  16. }
  17. }

输出:

  1. void Test_resize()
  2. {
  3. list<int> list_int{ 1,2,3,4,5 };
  4. cout << "resize前:" << endl;
  5. for (auto e : list_int)
  6. {
  7. cout << e << " ";
  8. }
  9. cout << endl;
  10. //给value,就用value初始化
  11. list_int.resize(10,6);
  12. cout << "resize前:" << endl;
  13. for (auto e : list_int)
  14. {
  15. cout << e << " ";
  16. }
  17. }

输出:

2.5.10、emplace系列接口

list 的emplace系列接口涉及到C++11可变参数模板以及右值引用的移动语义问题,在C++11讲解中对emplace的使用及原理做了详细讲解,大家请移步至下面这篇博文:

深入探索C++11 第三弹:C++11完结,迈进高效编程的新纪元-CSDN博客

3、list的迭代器失效问题(重点)

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

接下来看一个迭代器失效的例子:

  1. void TestListIterator1()
  2. {
  3. int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
  4. list<int> l(array, array + sizeof(array) / sizeof(array[0]));
  5. auto it = l.begin();
  6. while (it != l.end())
  7. {
  8. // erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值
  9. l.erase(it);
  10. ++it;
  11. }
  12. }

erase函数执行后,it 指向的节点被释放,此时 it 已经失效,下面对it++就会导致错误,这就是list的迭代器失效问题!

解决办法:

之前我们说过erase会返回被删除的节点的下一个位置的迭代器,所以我们只需要在使用it前将erase的返回值重新赋值给it即可.

  1. // 改正
  2. void TestListIterator()
  3. {
  4. int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
  5. list<int> l(array, array + sizeof(array) / sizeof(array[0]));
  6. auto it = l.begin();
  7. while (it != l.end())
  8. {
  9. it = l.erase(it);
  10. }
  11. }

4、list的模拟实现

4.1、List_Node的实现

  1. // List的节点类
  2. template<class T>
  3. struct ListNode
  4. {
  5. ListNode(const T& val = T())
  6. : _prev(nullptr)
  7. , _next(nullptr)
  8. , _val(val)
  9. {}
  10. ListNode<T>* _prev;
  11. ListNode<T>* _next;
  12. T _val;
  13. };

4.2、iterator 和const_iterator的封装

**List 的迭代器
迭代器有两种实现方式,具体应根据容器底层数据结构实现:

  1. 原生态指针,比如:vector
  2. 将原生态指针进行封装,因迭代器使用形式与指针完全相同,因此在自定义的类中必须实现以下方法:
    1. 指针可以解引用,迭代器的类中必须重载operator*()
    2. 指针可以通过->访问其所指空间成员,迭代器类中必须重载oprator->()
    3. 指针可以++向后移动,迭代器类中必须重载operator++()与operator++(int)
      至于operator--()/operator--(int)释放需要重载,根据具体的结构来抉择,双向链表可以向前 移动,所以需要重载,如果是forward_list就不需要重载--
    4. 迭代器需要进行是否相等的比较,因此还需要重载operator==()与operator!=()**
  1. template<class T, class Ref, class Ptr>
  2. class ListIterator
  3. {
  4. typedef ListNode<T> Node;
  5. typedef ListIterator<T, Ref, Ptr> Self;
  6. // Ref 和 Ptr 类型需要重定义下,实现反向迭代器时需要用到
  7. public:
  8. typedef Ref Ref;
  9. typedef Ptr Ptr;
  10. public:
  11. //
  12. // 构造
  13. ListIterator(Node* node = nullptr)
  14. : _node(node)
  15. {}
  16. //
  17. // 具有指针类似行为
  18. Ref operator*()
  19. {
  20. return _node->_val;
  21. }
  22. Ptr operator->()
  23. {
  24. return &(operator*());
  25. }
  26. //
  27. // 迭代器支持移动
  28. Self& operator++()
  29. {
  30. _node = _node->_next;
  31. return *this;
  32. }
  33. Self operator++(int)
  34. {
  35. Self temp(*this);
  36. _node = _node->_next;
  37. return temp;
  38. }
  39. Self& operator--()
  40. {
  41. _node = _node->_prev;
  42. return *this;
  43. }
  44. Self operator--(int)
  45. {
  46. Self temp(*this);
  47. _node = _node->_prev;
  48. return temp;
  49. }
  50. //
  51. // 迭代器支持比较
  52. bool operator!=(const Self& l)const
  53. {
  54. return _node != l._node;
  55. }
  56. bool operator==(const Self& l)const
  57. {
  58. return _node != l._node;
  59. }
  60. Node* _node;
  61. };
  62. template <class T>
  63. struct list_const_iterator
  64. {
  65. typedef List_Node<T> Node;
  66. typedef list_const_iterator<T> Self;
  67. Node* _node;
  68. //
  69. list_const_iterator(Node* node)
  70. :_node(node)
  71. {}
  72. const T& operator*()
  73. {
  74. return _node->_data;
  75. }
  76. Self& operator++()
  77. {
  78. _node = _node->_next;
  79. return *this;
  80. }
  81. const T* operator->()
  82. {
  83. return &_node->_data;
  84. }
  85. Self& operator++(int)
  86. {
  87. Self tmp = *this;
  88. _node = _node->_next;
  89. return tmp;
  90. }
  91. Self& operator--()
  92. {
  93. _node = _node->_prev;
  94. return *this;
  95. }
  96. Self& operator--(int)
  97. {
  98. Self tmp = *this;
  99. _node = _node->_prev;
  100. return tmp;
  101. }
  102. bool operator!=(const Self& s)const
  103. {
  104. return _node != s._node;
  105. }
  106. bool operator==(const Self& s)const
  107. {
  108. return _node == s._node;
  109. }
  110. };

4.3、 reverse_list_Iierator实现

*通过前面例子知道,反向迭代器的++就是正向迭代器的--,反向迭代器的--就是正向迭代器的++,***因此反向迭代器的实现可以借助正向迭代器,即:反向迭代器内部可以包含一个正向迭代器,对 **正向迭代器的接口进行包装即可。

  1. template<class Iterator>
  2. class ReverseListIterator
  3. {
  4. // 注意:此处typename的作用是明确告诉编译器,Ref是Iterator类中的一个类型,而不是静态成员变量
  5. // 否则编译器编译时就不知道Ref是Iterator中的类型还是静态成员变量
  6. // 因为静态成员变量也是按照 类名::静态成员变量名 的方式访问的
  7. public:
  8. typedef typename Iterator::Ref Ref;
  9. typedef typename Iterator::Ptr Ptr;
  10. typedef ReverseListIterator<Iterator> Self;
  11. public:
  12. //
  13. // 构造
  14. ReverseListIterator(Iterator it)
  15. : _it(it)
  16. {}
  17. //
  18. // 具有指针类似行为
  19. Ref operator*()
  20. {
  21. Iterator temp(_it);
  22. --temp;
  23. return *temp;
  24. }
  25. Ptr operator->()
  26. {
  27. return &(operator*());
  28. }
  29. //
  30. // 迭代器支持移动
  31. Self& operator++()
  32. {
  33. --_it;
  34. return *this;
  35. }
  36. Self operator++(int)
  37. {
  38. Self temp(*this);
  39. --_it;
  40. return temp;
  41. }
  42. Self& operator--()
  43. {
  44. ++_it;
  45. return *this;
  46. }
  47. Self operator--(int)
  48. {
  49. Self temp(*this);
  50. ++_it;
  51. return temp;
  52. }
  53. //
  54. // 迭代器支持比较
  55. bool operator!=(const Self& l)const
  56. {
  57. return _it != l._it;
  58. }
  59. bool operator==(const Self& l)const
  60. {
  61. return _it != l._it;
  62. }
  63. Iterator _it;
  64. };

4.4、list类模板的实现

  1. template<class T>
  2. class list
  3. {
  4. typedef ListNode<T> Node;
  5. public:
  6. // 正向迭代器
  7. typedef ListIterator<T, T&, T*> iterator;
  8. typedef ListIterator<T, const T&, const T&> const_iterator;
  9. // 反向迭代器
  10. typedef ReverseListIterator<iterator> reverse_iterator;
  11. typedef ReverseListIterator<const_iterator> const_reverse_iterator;
  12. public:
  13. ///
  14. // List的构造
  15. list()
  16. {
  17. CreateHead();
  18. }
  19. list(int n, const T& value = T())
  20. {
  21. CreateHead();
  22. for (int i = 0; i < n; ++i)
  23. push_back(value);
  24. }
  25. template <class Iterator>
  26. list(Iterator first, Iterator last)
  27. {
  28. CreateHead();
  29. while (first != last)
  30. {
  31. push_back(*first);
  32. ++first;
  33. }
  34. }
  35. list(const list<T>& l)
  36. {
  37. CreateHead();
  38. // 用l中的元素构造临时的temp,然后与当前对象交换
  39. list<T> temp(l.begin(), l.end());
  40. this->swap(temp);
  41. }
  42. list<T>& operator=(list<T> l)
  43. {
  44. this->swap(l);
  45. return *this;
  46. }
  47. ~list()
  48. {
  49. clear();
  50. delete _head;
  51. _head = nullptr;
  52. }
  53. ///
  54. // List的迭代器
  55. iterator begin()
  56. {
  57. return iterator(_head->_next);
  58. }
  59. iterator end()
  60. {
  61. return iterator(_head);
  62. }
  63. const_iterator begin()const
  64. {
  65. return const_iterator(_head->_next);
  66. }
  67. const_iterator end()const
  68. {
  69. return const_iterator(_head);
  70. }
  71. reverse_iterator rbegin()
  72. {
  73. return reverse_iterator(end());
  74. }
  75. reverse_iterator rend()
  76. {
  77. return reverse_iterator(begin());
  78. }
  79. const_reverse_iterator rbegin()const
  80. {
  81. return const_reverse_iterator(end());
  82. }
  83. const_reverse_iterator rend()const
  84. {
  85. return const_reverse_iterator(begin());
  86. }
  87. ///
  88. // List的容量相关
  89. size_t size()const
  90. {
  91. Node* cur = _head->_next;
  92. size_t count = 0;
  93. while (cur != _head)
  94. {
  95. count++;
  96. cur = cur->_next;
  97. }
  98. return count;
  99. }
  100. bool empty()const
  101. {
  102. return _head->_next == _head;
  103. }
  104. void resize(size_t newsize, const T& data = T())
  105. {
  106. size_t oldsize = size();
  107. if (newsize <= oldsize)
  108. {
  109. // 有效元素个数减少到newsize
  110. while (newsize < oldsize)
  111. {
  112. pop_back();
  113. oldsize--;
  114. }
  115. }
  116. else
  117. {
  118. while (oldsize < newsize)
  119. {
  120. push_back(data);
  121. oldsize++;
  122. }
  123. }
  124. }
  125. // List的元素访问操作
  126. // 注意:List不支持operator[]
  127. T& front()
  128. {
  129. return _head->_next->_val;
  130. }
  131. const T& front()const
  132. {
  133. return _head->_next->_val;
  134. }
  135. T& back()
  136. {
  137. return _head->_prev->_val;
  138. }
  139. const T& back()const
  140. {
  141. return _head->_prev->_val;
  142. }
  143. // List的插入和删除
  144. void push_back(const T& val)
  145. {
  146. insert(end(), val);
  147. }
  148. void pop_back()
  149. {
  150. erase(--end());
  151. }
  152. void push_front(const T& val)
  153. {
  154. insert(begin(), val);
  155. }
  156. void pop_front()
  157. {
  158. erase(begin());
  159. }
  160. // 在pos位置前插入值为val的节点
  161. iterator insert(iterator pos, const T& val)
  162. {
  163. Node* pNewNode = new Node(val);
  164. Node* pCur = pos._node;
  165. // 先将新节点插入
  166. pNewNode->_prev = pCur->_prev;
  167. pNewNode->_next = pCur;
  168. pNewNode->_prev->_next = pNewNode;
  169. pCur->_prev = pNewNode;
  170. return iterator(pNewNode);
  171. }
  172. // 删除pos位置的节点,返回该节点的下一个位置
  173. iterator erase(iterator pos)
  174. {
  175. // 找到待删除的节点
  176. Node* pDel = pos._node;
  177. Node* pRet = pDel->_next;
  178. // 将该节点从链表中拆下来并删除
  179. pDel->_prev->_next = pDel->_next;
  180. pDel->_next->_prev = pDel->_prev;
  181. delete pDel;
  182. return iterator(pRet);
  183. }
  184. void clear()
  185. {
  186. Node* cur = _head->_next;
  187. // 采用头删除删除
  188. while (cur != _head)
  189. {
  190. _head->_next = cur->_next;
  191. delete cur;
  192. cur = _head->_next;
  193. }
  194. _head->_next = _head->_prev = _head;
  195. }
  196. void swap(bite::list<T>& l)
  197. {
  198. std::swap(_head, l._head);
  199. }
  200. private:
  201. void CreateHead()
  202. {
  203. _head = new Node;
  204. _head->_prev = _head;
  205. _head->_next = _head;
  206. }
  207. private:
  208. Node* _head;
  209. };

5、list和vector的对比

std:list

  1. std::vector

底层存储结构
带头结点的双向循环链表。每个元素在内存中不连续存储,通过节点中的指针指向下一个元素。
*动态数组结构。元素在内存中是连续存储的。随机访问不支持高效的随机访问。要访问中间的元素,需要从头部(或尾部)开始遍历链表,时间复杂度为O(N),其中N是到目标元素的距离。***支持高效的随机访问。可以通过下标运算符

  1. []

直接访问元素,时间复杂度为O(1)。插入和删除元素在任意位置插入和删除元素效率高。在链表中间插入或删除一个元素,只需要调整指针,时间复杂度为O(1)(不考虑查找插入位置的时间)。在末尾插入元素效率高,时间复杂度一般为(当需要重新分配内存时可能会更复杂)。但是在中间或者开头插入 / 删除元素效率较低,因为需要移动插入 / 删除位置之后的所有元素,平均时间复杂度为O(N)。内存分配每次插入新元素时,只需分配新节点的内存,不需要重新分配整个容器的内存(除非内存不足)。当元素数量超过当前容量时,需要重新分配一块更大的连续内存空间,并且将原有元素复制到新空间中,这个过程可能比较耗时。迭代器失效删除操作只会使指向被操作元素的迭代器失效,其他迭代器不受影响。**
**在插入元素时,要给所有的迭代器重新赋值,因为 **

**插入元素有可能会导致重新扩容,致使原来迭代器 **

**失效,删除时,当前迭代器需要重新赋值否则会失 **


空间开销
除了存储元素本身,每个节点还需要额外的指针来维护链表结构,所以有一定的空间开销。

没有额外的指针开销,但是可能会因为内存对齐等原因

浪费少量空间。

使用 场景

需要高效存储,支持随机访问,不关心插入删除效率。

大量插入和删除操作,不关心随机访问。

6、小结

list也是STL中很基础同时也很重要的容器,是非常重要的数据结构之一,在操作系统,日志记录等方面都有很重要的应用,值得大家深入学习。

接下来会给大家带来C++ STL中其他容器的深度讲解,创作不易,还请多多互三支持。


本文转载自: https://blog.csdn.net/bite_zwy/article/details/144111716
版权归原作者 _Zwy@ 所有, 如有侵权,请联系我们删除。

“【深入探索 C++ STL 容器 list】 —— 编程世界的万能胶,数据结构中的百变精灵”的评论:

还没有评论