list类的详细讲解

【本节目标】
1. list的介绍及使用
2. list的深度剖析及模拟实现
3. list与vector的对比

1. list的介绍及使用

1.1 list的介绍

1. list 是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
2. list 的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向 其前一个元素和后一个元素。
3. list forward_list 非常相似:最主要的不同在于 forward_list 是单链表,只能朝前迭代,已让其更简单高 效。
4. 与其他的序列式容器相比 (array vector deque) list 通常在任意位置进行插入、移除元素的执行效率 更好。
5. 与其他序列式容器相比, list forward_list 最大的缺陷是不支持任意位置的随机访问,比如:要访问 list 的第6 个元素,必须从已知的位置 ( 比如头部或者尾部 ) 迭代到该位置,在这段位置上迭代需要线性的时间 开销;list 还需要一些额外的空间,以保存每个节点的相关联信息 ( 对于存储类型较小元素的大 list 来说这 可能是一个重要的因素)


1.2 list的使用

ist 中的接口比较多,此处类似,只需要掌握如何正确的使用,然后再去深入研究背后的原理,已达到可扩展 的能力。以下为list 中一些 常见的重要接口。


1.2.1 list的构造

#define _CRT_SECURE_NO_WARNINGS#include <iostream>
using namespace std;
#include <list>
#include <vector>// list的构造
void TestList1()
{list<int> l1;                         // 构造空的l1list<int> l2(4, 100);                 // l2中放4个值为100的元素list<int> l3(l2.begin(), l2.end());  // 用l2的[begin(), end())左闭右开的区间构造l3list<int> l4(l3);                    // 用l3拷贝构造l4// 以数组为迭代器区间构造l5int array[] = { 16,2,77,29 };list<int> l5(array, array + sizeof(array) / sizeof(int));// 列表格式初始化C++11list<int> l6{ 1,2,3,4,5 };// 用迭代器方式打印l5中的元素list<int>::iterator it = l5.begin();while (it != l5.end()){cout << *it << " ";++it;}       cout << endl;// C++11范围for的方式遍历for (auto& e : l5)cout << e << " ";cout << endl;
}

1.2.2 list iterator的使用

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

【注意】
1. begin end 为正向迭代器,对迭代器执行 ++ 操作,迭代器向后移动
2. rbegin(end) rend(begin) 为反向迭代器,对迭代器执行 ++ 操作,迭代器向前移动


// list迭代器的使用
// 注意:遍历链表只能用迭代器和范围for
void PrintList(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;
}void TestList2()
{int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };list<int> l(array, array + sizeof(array) / sizeof(array[0]));// 使用正向迭代器正向list中的元素// list<int>::iterator it = l.begin();   // C++98中语法auto it = l.begin();                     // C++11之后推荐写法while (it != l.end()){cout << *it << " ";++it;}cout << endl;// 使用反向迭代器逆向打印list中的元素// list<int>::reverse_iterator rit = l.rbegin();auto rit = l.rbegin();while (rit != l.rend()){cout << *rit << " ";++rit;}cout << endl;
}

1.2.3 list capacity

1.2.4 list element access

1.2.5 list modifiers


// list插入和删除
// push_back/pop_back/push_front/pop_front
void TestList3()
{int array[] = { 1, 2, 3 };list<int> L(array, array + sizeof(array) / sizeof(array[0]));// 在list的尾部插入4,头部插入0L.push_back(4);L.push_front(0);PrintList(L);// 删除list尾部节点和头部节点L.pop_back();L.pop_front();PrintList(L);
}// insert /erase 
void TestList4()
{int array1[] = { 1, 2, 3 };list<int> L(array1, array1 + sizeof(array1) / sizeof(array1[0]));// 获取链表中第二个节点auto pos = ++L.begin();cout << *pos << endl;// 在pos前插入值为4的元素L.insert(pos, 4);PrintList(L);// 在pos前插入5个值为5的元素L.insert(pos, 5, 5);PrintList(L);// 在pos前插入[v.begin(), v.end)区间中的元素vector<int> v{ 7, 8, 9 };L.insert(pos, v.begin(), v.end());PrintList(L);// 删除pos位置上的元素L.erase(pos);PrintList(L);// 删除list中[begin, end)区间中的元素,即删除list中的所有元素L.erase(L.begin(), L.end());PrintList(L);
}
// resize/swap/clear
void TestList5()
{// 用数组来构造listint array1[] = { 1, 2, 3 };list<int> l1(array1, array1 + sizeof(array1) / sizeof(array1[0]));PrintList(l1);// 交换l1和l2中的元素list<int> l2;l1.swap(l2);PrintList(l1);PrintList(l2);// 将l2中的元素清空l2.clear();cout << l2.size() << endl;
}
list 中还有一些操作,需要用到时大家可参阅 list 的文档说明。

1.2.6 list的迭代器失效

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

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

2. list的模拟实现

2.1 模拟实现list

要模拟实现 list ,必须要熟悉 list 的底层结构以及其接口的含义,通过上面的学习,这些内容已基本掌握,现 在我们来模拟实现list
#pragma once
#include <assert.h>
#include <iostream>namespace xyl
{template<class T>//list节点类struct ListNode{ListNode(const T& val = T()):_pPrev(nullptr), _pNext(nullptr),_val(val){}ListNode<T>* _pPrev;ListNode<T>* _pNext;T _val;};//List迭代器类template<class T,class Ref,class Ptr>struct ListIterator{typedef ListNode<T>* PNode;typedef ListIterator<T, Ref, Ptr> Self;ListIterator(PNode pNode = nullptr):_pNode(pNode){}ListIterator(const Self & l):_pNode(l._pNode){}T& operator*(){return _pNode->_val;}T* operator->(){return &(_pNode->_val);}Self& operator++(){_pNode = _pNode->_pNext;return *this;}Self operator++(int){Self tmp(*this);_pNode = _pNode->_pNext;return tmp;}Self& operator--(){_pNode = _pNode->_pPrev;return *this;}Self& operator--(int){Self tmp(*this);_pNode = _pNode->_pPrev;return tmp;}bool operator==(const Self& l){return _pNode == l._pNode;}bool operator!=(const Self& l){return _pNode != l._pNode;}PNode _pNode;};//list类template< class T >class list{typedef ListNode<T> Node;typedef Node* PNode;public:typedef ListIterator<T, T&,  T*> iterator;typedef ListIterator<T,const T&, const T*> const_iterator;public:void init_empty(){_head = new Node;_head->_pPrev = _head;_head->_pNext = _head;size = 0;}list(){init_empty();}list(int n, const T& val = T()){init_empty();for (int i = 0;i < n;i++){push_back(val);}}template <class Iterator>list(Iterator first, Iterator last){init_empty();while (first != last){push_back(*first);first++;}}list(const list<T>& l){init_empty();const_iterator it = l.begin();while (it != l.end()){push_back(*it);it++;}}~list(){clean();delete _head;_head = nullptr;}void clean(){iterator it = begin();while (it != end()){it=erase(it);}_head->_pNext = _head;_head->_pPrev = _head;}list<T>& operator=(const list<T>& l){list<T> tmp(l);swap(tmp);return *this;}size_t _size(){return size;}bool empty(){return size == 0;}T& front(){return _head->_pNext->_val;}T& back(){return _head->_pPrev->_val;}const T& front() const{return _head->_pNext->_val;}const T& back() const{return _head->_pPrev->_val;}void push_back(const T& val){/*PNode cur= new Node(val);PNode tail = _head->_pPrev;cur->_pPrev = tail;cur->_pNext = _head;tail->_pNext = cur;_head->_pPrev = cur;size++;*/insert(end(), val);}void push_front(const T& val){insert(begin(), val);}void pop_back(){erase(--end());}void pop_front(){erase(begin());}iterator insert(iterator pos, const T& val){PNode newnode = new Node(val);PNode cur = pos._pNode;PNode prev = cur->_pPrev;prev->_pNext = newnode;newnode->_pPrev = prev;newnode->_pNext = cur;cur->_pPrev = newnode;size++;return iterator(newnode);}iterator erase(iterator pos){//找到删除节点PNode del = pos._pNode;//存储删除节点的下一位当返回值PNode tmp = del->_pNext;PNode next = del->_pNext;PNode prev = del->_pPrev;prev->_pNext = next;next->_pPrev = prev;delete del;size--;return iterator(tmp);}iterator begin() {return (_head->_pNext);}iterator end() {return (_head);}const_iterator begin() const{return (_head->_pNext);}const_iterator end() const{return (_head);}void swap(list<T>& l){std::swap(_head, l._head);std::swap(size, l.size);}PNode _head;size_t size;};
}

#include <iostream>#include "list.h"using namespace std;void test_list1()
{xyl::list<int> list1;list1.push_back(1);list1.push_back(2);list1.push_back(3);list1.push_back(4);xyl::list<int>:: iterator it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;cout << list1.size;cout << endl;xyl::list<int> list2(10,1);xyl::list<int>::iterator it2 = list2.begin();while (it2 != list2.end()){cout << (*it2) << ' ';++it2;}cout << endl;}void test_list2()
{xyl::list<int> list1;list1.push_back(1);list1.push_back(2);list1.push_back(3);list1.push_back(4);xyl::list<int>::iterator it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;xyl::list<int> list2(++list1.begin(),list1.end());xyl::list<int>::iterator it2 = list2.begin();while (it2 != list2.end()){cout << (*it2) << ' ';++it2;}cout << endl;xyl::list<int> list3(list2);xyl::list<int>::iterator it3 = list3.begin();while (it3 != list3.end()){cout << (*it3) << ' ';++it3;}cout << endl;
}void test_list3()
{xyl::list<int> list1;list1.push_back(1);list1.push_back(2);list1.push_back(3);list1.push_back(4);xyl::list<int>::iterator it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;xyl::list<int> list2;list2 = list1;xyl::list<int>::iterator it2 = list2.begin();while (it2 != list2.end()){cout << (*it2) << ' ';++it2;}cout << endl;cout << list2.front() << endl;cout << list2.back() << endl;
}void test_list4()
{xyl::list<int> list1;list1.push_back(1);list1.push_back(2);list1.push_back(3);list1.push_back(4);list1.erase(list1.begin());xyl::list<int>::iterator it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}list1.clean();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}}void test_list5()
{xyl::list<int> list1;list1.push_back(1);list1.push_back(2);list1.push_back(3);list1.push_back(4);list1.insert(list1.begin(), 3);xyl::list<int>::iterator it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;list1.pop_back();it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;list1.pop_front();it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;list1.push_front(5);it1 = list1.begin();while (it1 != list1.end()){cout << (*it1) << ' ';++it1;}cout << endl;
}int main()
{test_list5();return 0;
}

2.2 list的反向迭代器

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

template<class Iterator>
class ReverseListIterator
{// 注意:此处typename的作用是明确告诉编译器,Ref是Iterator类中的类型,而不是静态成员变量// 否则编译器编译时就不知道Ref是Iterator中的类型还是静态成员变量// 因为静态成员变量也是按照 类名::静态成员变量名 的方式访问的
public:typedef typename Iterator::Ref Ref;typedef typename Iterator::Ptr Ptr;typedef ReverseListIterator<Iterator> Self;
public://// 构造ReverseListIterator(Iterator it) : _it(it) {}//// 具有指针类似行为Ref operator*() {Iterator temp(_it);--temp;return *temp;}Ptr operator->() { return &(operator*()); }//// 迭代器支持移动Self& operator++() {--_it;return *this;}Self operator++(int) {Self temp(*this);--_it;return temp;}Self& operator--() {++_it;return *this;}Self operator--(int){Self temp(*this);++_it;return temp;}//// 迭代器支持比较bool operator!=(const Self& l)const { return _it != l._it; }bool operator==(const Self& l)const { return _it != l._it; }Iterator _it;
};

3. listvector的对比

vector list 都是 STL 中非常重要的序列式容器,由于两个容器的底层结构不同,导致其特性以及应用场景不 同,其主要不同如下:

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/905116.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第十节:图像处理基础-图像算术运算 (加法、减法、混合)

引言 在计算机视觉领域,图像算术运算是最基础却至关重要的核心技术。无论是实现简单的图片合成、开发智能监控系统,还是构建复杂的医学影像分析工具,加减运算和混合操作都扮演着关键角色。OpenCV作为最流行的计算机视觉库,提供了完善的图像处理函数集。本文将深入解析三种…

【React 的useState钩子详解】

React 的 useState 钩子详解 useState 是 React 中最基础且最常用的 Hook 之一&#xff0c;它允许你在函数组件中添加和管理状态。 基本语法 const [state, setState] useState(initialState);initialState: 状态的初始值&#xff0c;可以是任何 JavaScript 数据类型state:…

vue 中的数据代理

在 Vue 中&#xff0c;数据代理&#xff08;Data Proxy&#xff09; 是 Vue 实现 MVVM 模式 的关键技术之一。Vue 使用数据代理让你可以通过 this.message 访问 data.message&#xff0c;而不需要写 this.data.message —— 这大大简化了模板和逻辑代码。 我们来深入理解它的本…

基于Python的网络电子书阅读系统

标题:基于Python的网络电子书阅读系统 内容:1.摘要 随着数字化阅读的兴起&#xff0c;网络电子书阅读需求日益增长。本研究旨在开发一个基于Python的网络电子书阅读系统&#xff0c;以满足用户便捷阅读电子书的需求。采用Python的Flask框架搭建Web服务器&#xff0c;结合SQLit…

基于SpringBoot的抽奖系统测试报告

一、编写目的 本报告为抽奖系统测试报告&#xff0c;本项目可用于团体抽奖活动&#xff0c;包括了用户注册&#xff0c;用户登录&#xff0c;修改奖项以及抽奖等功能。 二、项目背景 抽奖系统采用前后端分离的方法来实现&#xff0c;同时使用了数据库来存储相关的数据&…

Apache Flink 与 Flink CDC:概念、联系、区别及版本演进解析

Apache Flink 与 Flink CDC:概念、联系、区别及版本演进解析 在实时数据处理和流式计算领域,Apache Flink 已成为行业标杆。而 Flink CDC(Change Data Capture) 作为其生态中的重要组件,为数据库的实时变更捕获提供了强大的能力。 本文将从以下几个方面进行深入讲解: 什…

单片机-STM32部分:9、定时器

飞书文档https://x509p6c8to.feishu.cn/wiki/A749wx8T0ioqfgkzZKlc9poknUf SMT32F1系列共有8个定时器&#xff1a; 基本定时器&#xff08;TIM6、TIM7&#xff09; 通用定时器&#xff08;TIM2、TIM3、TIM4、TIM5&#xff09; 高级定时器&#xff08;TIM1、TIM8&#xff09…

uniapp-商城-51-后台 商家信息(logo处理)

前面对页面基本进行了梳理和说明&#xff0c;特别是对验证规则进行了阐述&#xff0c;并对自定义规则的兼容性进行了特别补充&#xff0c;应该说是干货满满。不知道有没有小伙伴已经消化了。 下面我们继续前进&#xff0c;说说页面上的logo上传组件&#xff0c;主要就是uni-fil…

ideal创建Springboot项目(Maven,yml)

以下是使用 IntelliJ IDEA 创建基于 Maven 的 Spring Boot 项目并使用 YAML 配置文件的详细步骤&#xff1a; 一、创建 Spring Boot 项目 启动项目创建向导 打开 IntelliJ IDEA&#xff0c;点击“File”->“New”->“Project”。 在弹出的“New Project”窗口中&#…

MATLAB中矩阵和数组的区别

文章目录 前言环境配置1. 数据结构本质2. 运算规则&#xff08;1&#xff09;基本运算&#xff08;2&#xff09;特殊运算 3. 函数与操作4. 高维支持5. 创建方式 前言 在 MATLAB 中&#xff0c;矩阵&#xff08;Matrix&#xff09; 和 数组&#xff08;Array&#xff09; 的概…

iTwin 数据报表(只是简单的原型不代表实现)

大概想法是 前端从schema和class中选中感兴趣的property内容生成ecsql语句传递给后端后端解析ecsql并提供公开接口给各个分析工具&#xff0c;如excel&#xff0c;poewerBI等&#xff08;Odata或者直接选择来自网站&#xff09;再由分析工具做进一步的处 还未想好的点 如何存…

Spring AI 系列——使用大模型对文本内容分类归纳并标签化输出

原理概述 利用大语言模型&#xff08;LLM&#xff09;实现文本分类&#xff0c;核心思想是通过预训练模型理解输入文本的语义&#xff0c;并将其映射到预先定义好的分类标签。在这个过程中&#xff0c;我们借助 Spring AI Alibaba 提供的能力&#xff0c;使用阿里云 DashScope…

LeetCode 高频题实战:如何优雅地序列化和反序列化字符串数组?

文章目录 摘要描述题解答案题解代码分析编码方法解码方法 示例测试及结果时间复杂度空间复杂度总结 摘要 在分布式系统中&#xff0c;数据的序列化与反序列化是常见的需求&#xff0c;尤其是在网络传输、数据存储等场景中。LeetCode 第 271 题“字符串的编码与解码”要求我们设…

GitHub打开缓慢甚至失败的解决办法

在C:\Windows\System32\drivers\etc的hosts中增加如下内容&#xff1a; 20.205.243.166 github.com 199.59.149.236 github.global.ssl.fastly.net185.199.109.153 http://assets-cdn.github.com 185.199.108.153 http://assets-cdn.github.com 185.199.110.153 http://asset…

重生之我在2024学Fine-tuning

一、Fine-tuning&#xff08;微调&#xff09;概述 Fine-tuning&#xff08;微调&#xff09;是机器学习和深度学习中的一个重要概念&#xff0c;特别是在预训练模型的应用上。它指的是在模型已经通过大量数据训练得到一个通用的预训练模型后&#xff0c;再针对特定的任务或数据…

计算机网络 4-2-1 网络层(IPv4)

2 IPv4分组 各协议之间的关系 IP协议(Internet Protocol, 网际协议)是互联网的核心&#xff01; ARP协议用于查询同一网络中的<主机IP地址&#xff0c;MAC地址>之间的映射关系 ICMP协议用于网络层实体之间相互通知“异常事件” IGMP协议用于实现IP组播 2.1 结构<首…

Docker中运行的Chrome崩溃问题解决

问题 各位看官是否在 Docker 容器中的 Linux 桌面环境&#xff08;如Xfce&#xff09;上启动Chrome &#xff0c;遇到了令人沮丧的频繁崩溃问题&#xff1f;尤其是在打开包含图片、视频的网页&#xff0c;或者进行一些稍复杂的操作时&#xff0c;窗口突然消失&#xff1f;如果…

K8S cgroups详解

以下是 Kubernetes 中 cgroups&#xff08;Control Groups&#xff09; 的详细解析&#xff0c;涵盖其核心原理、在 Kubernetes 中的具体应用及实践操作&#xff1a; 一、cgroups 基础概念 1. 是什么&#xff1f; cgroups 是 Linux 内核提供的 资源隔离与控制机制&#xff0c…

javaer快速从idea转战vscode

插件安装列表 在插市场安装下面插件 Extension Pack for JavaSpring Boot Tools 配置文件提示Database Client Database/No-SQL管理工具httpYac - Rest Client .http文件编辑、API测试工具 https://httpyac.github.io/guide/request.htmlGit Graph 图形化Git工具XML by Red H…

[项目总结] 抽奖系统项目技术应用总结

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏: &#x1f9ca; Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection与…