C++STL库中的list
文章目录
- list的介绍及使用
- list的常用接口
- list的模拟实现
- list与vector的对比
一、list的介绍及使用
- 1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
- 2. list的底层是双向带头循环链表结构,双向带头循环链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
- 3. list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高效。
- 4. 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好。
- 5. 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,比如:要访问list的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间
- 开销;list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这可能是一个重要的因素)
二、list的常用接口
1.list的构造函数
default (1) list();explicit list (const allocator_type& alloc);构造一个没有元素的空容器。
fill (2) explicit list (size_type n, const allocator_type& alloc = allocator_type()); list (size_type n, const value_type& val, const allocator_type& alloc = allocator_type());构造一个包含n个元素的容器。每个元素都是val。
range (3) template <class InputIterator> list (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());构造一个包含与范围[first,last]一样多的元素的容器,每个元素都以相同的顺序从该范围中的相应元素构造而成。
copy (4) list (const list& x); list (const list& x, const allocator_type& alloc);以相同的顺序构造一个包含x中每个元素的副本的容器。
move (5) list (list&& x);list (list&& x, const allocator_type& alloc);右值引用构造
initializer list (6) list (initializer_list<value_type> il, const allocator_type& alloc = allocator_type());构造一个通过初始化列表的方式
#include <iostream>
#include <list>int main()
{std::list<int> l1; // 构造空的l1std::list<int> l2(4, 100); // l2中放4个值为100的元素std::list<int> l3(l2.begin(), l2.end()); // 用l2的[begin(), end())左闭右开的区间构造l3std::list<int> l4(l3); // 用l3拷贝构造l4// 以数组为迭代器区间构造l5int array[] = { 16,2,77,29 };std::list<int> l5(array, array + sizeof(array) / sizeof(int));// 列表格式初始化C++11std::list<int> l6{ 1,2,3,4,5 };// 用迭代器方式打印l5中的元素std::list<int>::iterator it = l5.begin();while (it != l5.end()){std::cout << *it << " ";++it;}std::cout << std::endl;// C++11范围for的方式遍历for (auto& e : l5)std::cout << e << " ";std::cout << std::endl;return 0;
}
2.list iterator的使用
函数声明 接口说明begin + end 返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器 (即头结点)rbegin + rend 返回第一个元素的reverse_iterator,即end位置,返回最后一个元素下一个位置的reverse_iterator,即begin位置

#include <iostream>
#include <list>int main()
{std::list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);for (auto it = lt.begin(); it != lt.end(); it++)std::cout << *it << " ";std::cout << std::endl;for (auto x : lt)std::cout << x << " ";std::cout << std::endl;return 0;
}
3.list相关容量操作
函数声明 接口说明empty 检测list是否为空,是返回true,否则返回falsesize 返回list中有效节点的个数
#include <iostream>
#include <list>int main()
{std::list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);std::cout << lt.size() << std::endl;std::cout << lt.empty() << std::endl;return 0;
}
4.list相关访问操作
函数声明 接口说明front 返回list的第一个节点中值的引用back 返回list的最后一个节点中值的引用
#include <iostream>
#include <list>int main()
{std::list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);std::cout << lt.front() << std::endl;std::cout << lt.back() << std::endl;return 0;
}
5.list相关修改操作
函数声明 接口说明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中的有效元素
#include <iostream>
#include <vector>
#include <list>// list迭代器的使用
// 注意:遍历链表只能用迭代器和范围for
void PrintList(const std::list<int>& l)
{// 注意这里调用的是list的 begin() const,返回list的const_iterator对象for (std::list<int>::const_iterator it = l.begin(); it != l.end(); ++it){std::cout << *it << " ";// *it = 10; 编译不通过}std::cout << std::endl;
}// list插入和删除
// push_back/pop_back/push_front/pop_front
void TestList3()
{int array[] = { 1, 2, 3 };std::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 };std::list<int> L(array1, array1 + sizeof(array1) / sizeof(array1[0]));// 获取链表中第二个节点auto pos = ++L.begin();std::cout << *pos << std::endl;// 在pos前插入值为4的元素L.insert(pos, 4);PrintList(L);// 在pos前插入5个值为5的元素L.insert(pos, 5, 5);PrintList(L);// 在pos前插入[v.begin(), v.end)区间中的元素std::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 };std::list<int> l1(array1, array1 + sizeof(array1) / sizeof(array1[0]));PrintList(l1);// 交换l1和l2中的元素std::list<int> l2;l1.swap(l2);PrintList(l1);PrintList(l2);// 将l2中的元素清空l2.clear();std::cout << l2.size() << std::endl;
}int main()
{TestList3();TestList4();TestList5();return 0;
}
6.list容器相关独特操作
splice 将元素从一个链表转移到另一个链表(公共成员函数)
remove 删除具有特定值的元素(公共成员函数)remove_if 删除满足条件的元素(公共成员函数模板)
unique 删除重复值(公共成员函数)
mergemerge 合并已排序的列表(公共成员功能)
sort 对容器中的元素排序(公共成员函数)reverse 颠倒元素的顺序(公共成员函数)
三、list的模拟实现
1.list的节点结构
template<class T>struct list_node{T _data;//数据域list_node<T>* _prev;//前驱指针list_node<T>* _next;//后继指针list_node(const T& val=T()):_data(val),_prev(nullptr),_next(nullptr){}};
2.list的常用接口模拟
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;const_iterator begin()const;const_iterator end()const;iterator begin();iterator end();list();template<class InputIterator>list(InputIterator first,InputIterator last);list(const list<T>& lt);list<T>& operator=(list<T> lt);~list();size_t size();bool empty();void push_back(const T& val);void push_front(const T& val);iterator insert(iterator pos, const T& x);iterator erase(iterator pos);void pop_back();void pop_front();void clear();private:Node* _head;};
3.list的迭代器
1.迭代器相关结构组成

// 像指针一样的对象template<class T, class Ref, class Ptr>struct __list_iterator{typedef list_node<T> Node;typedef __list_iterator<T, Ref, Ptr> iterator;typedef bidirectional_iterator_tag iterator_category;typedef T value_type;typedef Ptr pointer;typedef Ref reference;typedef ptrdiff_t difference_type;Node* _node;__list_iterator(Node* node):_node(node){}bool operator!=(const iterator& it) const;bool operator==(const iterator& it) const;Ref operator*();Ptr operator->();iterator& operator++();iterator operator++(int);iterator& operator--();iterator operator--(int);};
2.迭代器结构实现
template<class T,class Ref,class Ptr>struct __list_iterator{typedef list_node<T> Node;typedef __list_iterator<T, Ref, Ptr> iterator;typedef std::bidirectional_iterator_tag iterator_category;typedef T value_type;typedef Ptr pointer;typedef Ref reference;typedef ptrdiff_t difference_type;Node* _node;__list_iterator(Node* node):_node(node){};bool operator!=(const iterator& it)const{return _node != it._node;}bool operator==(const iterator& it)const{return _node == it._node;}Ref operator*(){return _node->_data;}Ptr operator->(){return &(operator*());}iterator& operator++(){_node = _node->_next;return *this;}iterator operator++(int){iterator tmp(*this);_node = _node->_next;return tmp;}iterator& operator--(){_node = _node->_prev;return *this;}iterator operator--(int){iterator tmp(*this);_node = _node->_prev;return tmp;}};
4.list的成员函数
1.list的构造函数
// 默认构造函数
list()
{// 构造头节点,自己指向自己_head = new Node;_head->_prev = _head;_head->_next = _head;
}// 用迭代器区间初始化[first,last)
template<class InputIterator>
list(InputIterator first, InputIterator last):_head(new Node)
{_head->_prev = _head;_head->_next = _head;while (first != last){push_back(*first);first++;}
}
2.list的拷贝构造函数
//拷贝构造函数(深拷贝)
// lt2(lt1)
list(const list<T>& lt):_head(new Node)
{_head->_prev = _head;_head->_next = _head;for (const auto& e : lt){push_back(e);}
}// 拷贝构造函数(深拷贝)
list(const list<T>& lt):_head(new Node)
{_head->_prev = _head;_head->_next = _head;list<T> tmp(lt.begin(), lt.end());std::swap(_head, tmp._head);
}
3.list的赋值运算符重载函数
//深拷贝
list<T>& operator=(const list<T>& lt)
{if (this != <) {clear();for (const auto& e : lt){push_back(e);}}return *this;
}list<T>& operator=(list<T> lt)
{std::swap(_head, lt._head);return *this;
}
4.list的析构函数
~list()
{//方法一Node* cur = _head->_next;while (cur != _head) {Node* next = cur->_next; delete cur; cur = next;}delete _head; _head = nullptr;//方法二:复用 clear 函数的代码clear();delete _head;_head = nullptr;
}
5.list其他相关结构函数
void clear(){iterator it = begin();while (it != end()){it = erase(it);}}void push_back(const T& x){//Node* tail = _head->_prev;//Node* newnode = new Node(x);_head tail newnode//tail->_next = newnode;//newnode->_prev = tail;//newnode->_next = _head;//_head->_prev = newnode;insert(end(), x);}void push_front(const T& x){insert(begin(), x);}iterator insert(iterator pos, const T& x){Node* cur = pos._node;Node* prev = cur->_prev;Node* newnode = new Node(x);// prev newnode curprev->_next = newnode;newnode->_prev = prev;newnode->_next = cur;cur->_prev = newnode;return iterator(newnode);}void pop_back(){erase(--end());}void pop_front(){erase(begin());}iterator erase(iterator pos){assert(pos != end());Node* cur = pos._node;Node* prev = cur->_prev;Node* next = cur->_next;prev->_next = next;next->_prev = prev;delete cur;return iterator(next);}
5.list的迭代器失效
#include <iostream>
#include <list>void testlistiterator1()
{int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };std::list<int> l(array, array + sizeof(array) / sizeof(array[0]));auto it = l.begin();while (it != l.end()){// erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值it = l.erase(it);it++;}
}int main()
{testlistiterator1();return 0;
}
四、list与vector的对比

相关文章:
C++STL库中的list
文章目录 list的介绍及使用 list的常用接口 list的模拟实现 list与vector的对比 一、list的介绍及使用 1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。 2. list的底层是双向带头循环链表结构,双向带头循…...
【LeetCode 75】第十七题(1493)删掉一个元素以后全为1的最长子数组
目录 题目: 示例: 分析: 代码运行结果: 题目: 示例: 分析: 给一个数组,求删除一个元素以后能得到的连续的最长的全是1的子数组。 我们可以先单独统计出连续为1的子数组分别长度…...
配置IPv6 over IPv4 GRE隧道示例
组网需求 如图1,两个IPv6网络分别通过SwitchA和SwitchC与IPv4公网中的SwitchB连接,客户希望两个IPv6网络中的PC1和PC2实现互通。 其中PC1和PC2上分别指定SwitchA和SwitchC为自己的缺省网关。 图1 配置IPv6 over IPv4 GRE隧道组网图 配置思路 要实现I…...
Google Earth Engine谷歌地球引擎提取多波段长期反射率数据后绘制折线图并导出为Excel
本文介绍在谷歌地球引擎GEE中,提取多年遥感影像多个不同波段的反射率数据,在GEE内绘制各波段的长时间序列走势曲线图,并将各波段的反射率数据与其对应的成像日期一起导出为.csv文件的方法。 本文是谷歌地球引擎(Google Earth Engi…...
第三大的数
414、第三大的数 class Solution {public int thirdMax(int[] nums) {Arrays.sort(nums);int tempnums[0];int ansnums[0];int count 0;// if(nums.length<3){// return nums[nums.length-1];// }// else {for(int inums.length-1;i>0;i--){if (nums[i]>nums[i…...
正则表达式中的方括号[]有什么用?
在正则表达式中,方括号 [] 是用于定义字符集合的元字符。它在正则表达式中有以下作用: 匹配字符集合中的任意一个字符:方括号中列出的字符,表示在这个位置可以匹配这些字符中的任意一个。例如,[abc] 将匹配任意一个字符…...
SQL编写规范
文章目录 1.命名规范:2.库表设计:3.查询数据:4.修改数据:5.索引创建: 1.命名规范: 1.库名、表名、字段名,必须使用小写字母或数字,不得超过30个字符。 2.库名、表名、字段名&#…...
Azure pipeline自动化打包发布
pipeline自动化,提交代码后,就自动打包,打包成功后自动发布 第一步 pipeline提交代码后,自动打包。 1 在Repos,分支里选择要触发的分支,这里选择cn_china,对该分支设置分支策略 2 在生产验证中增加新的策略 3 在分支安…...
【算法提高:动态规划】1.4 状态机模型 TODO
文章目录 例题列表1049. 大盗阿福(其实就是打家劫舍)1057. 股票买卖 IV(k笔交易)1058. 股票买卖 V(冷冻期)1052. 设计密码⭐⭐⭐🚹🚹🚹(TODO)1053…...
ip link add 命令
ip link add veth0 type veth peer name veth1 这条命令主要用于在 Linux 操作系统中创建一个新的 veth(虚拟以太网) 对,这是一种虚拟网络设备,用于在 Linux 命名空间(namespaces)之间创建网络连接。此命令将创建两个设备…...
unity事件处理
方法调用 //发送事件 【发送事件码,发送消息内容】 EventCenterUtil.Broadcast(EventCenterUtil.EventType.Joystick, ui);//监听无参事件 EventCenterUtil.AddListener(EventCenterUtil.EventType.Joystick, show); public void show(){}//发送事件 有参事件 Eve…...
《ChatGPT原理最佳解释,从根上理解ChatGPT》
【热点】 2022年11月30日,OpenAI发布ChatGPT(全名:Chat Generative Pre-trained Transformer), 即聊天机器人程序 ,开启AIGC的研究热潮。 ChatGPT是人工智能技术驱动的自然语言处理工具,它能够…...
大数据Flink(五十):流式计算简介
文章目录 流式计算简介 一、数据的时效性 二、流式计算和批量计算...
13-4_Qt 5.9 C++开发指南_基于QWaitCondition 的线程同步_Wait
在多线程的程序中,多个线程之间的同步实际上就是它们之间的协调问题。例如上一小节讲到的3个线程的例子中,假设 threadDAQ 写满一个缓冲区之后,threadShow 和 threadSaveFile 才能对缓冲区进行读操作。前面采用的互斥量和基于 OReadWriteLock…...
STM32(HAL)多串口进行重定向(printf函数发送数据)
目录 1、简介 2.1 基础配置 2.1.1 SYS配置 2.1.2 RCC配置 2.2 串口外设配置 2.3 项目生成 3、KEIL端程序整合 4、效果测试 1、简介 在HAL库中,常用的printf函数是无法使用的。本文通过重映射实现在HAL库多个串口可进行类似printf函数的操作。 2.1 基础配置 2.…...
29_互联网(The Internet)(IP数据包;UDP;TCP;DNS;OSI)
上篇介绍了计算机网络的基础知识,也提到互联网(The Internet),本篇将会详细介绍互联网(The Internet)。 文章目录 1. 互联网(The Internet)组成及数据包传输过程2. IP 数据包的不足3…...
xShell常用命令
xShell常用命令 一、文件夹目录1、cd-更改目录2、mkdir-建立目录3、rm-删除目录4、pwd-查看当前路径5、rmdir-删除空目录 二、文件操作1、cat-显示文件内容2、diff-比较文件内容3、查看文件的名字和后缀4、ls-列出文件5、cp-复制文件6、mv-移动和重命名文件找不同:选…...
React性能优化之Memo、useMemo
文章目录 React.memo两种方式参数应用场景 拓展useMemouseMemo(calculateValue, dependencies) 参考资料 React.memo React 的渲染机制,组件内部的 state 或者 props 一旦发生修改,整个组件树都会被重新渲染一次,即时子组件的参数没有被修改&…...
IDEA开启并配置services窗口
前言: 一般一个spring cloud项目中大大小小存在几个十几个module编写具体的微服务项目。此时,如果要调试测需要依次启动各个项目比较麻烦。 方法一: 默认第一次打开项目的时候,idea会提示是否增加这个选项卡,如果你没…...
vue2企业级项目(三)
vue2企业级项目(三) 引入mockjs,i18n 1、mockjs 项目下载依赖 npm install --save-dev mock根目录创建mock文件夹,并创建mock/index.js import Mock from "mockjs";// 设置全局延时 没有延时的话有时候会检测不到数据…...
基于算法竞赛的c++编程(28)结构体的进阶应用
结构体的嵌套与复杂数据组织 在C中,结构体可以嵌套使用,形成更复杂的数据结构。例如,可以通过嵌套结构体描述多层级数据关系: struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...
k8s从入门到放弃之Ingress七层负载
k8s从入门到放弃之Ingress七层负载 在Kubernetes(简称K8s)中,Ingress是一个API对象,它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress,你可…...
.Net框架,除了EF还有很多很多......
文章目录 1. 引言2. Dapper2.1 概述与设计原理2.2 核心功能与代码示例基本查询多映射查询存储过程调用 2.3 性能优化原理2.4 适用场景 3. NHibernate3.1 概述与架构设计3.2 映射配置示例Fluent映射XML映射 3.3 查询示例HQL查询Criteria APILINQ提供程序 3.4 高级特性3.5 适用场…...
23-Oracle 23 ai 区块链表(Blockchain Table)
小伙伴有没有在金融强合规的领域中遇见,必须要保持数据不可变,管理员都无法修改和留痕的要求。比如医疗的电子病历中,影像检查检验结果不可篡改行的,药品追溯过程中数据只可插入无法删除的特性需求;登录日志、修改日志…...
家政维修平台实战20:权限设计
目录 1 获取工人信息2 搭建工人入口3 权限判断总结 目前我们已经搭建好了基础的用户体系,主要是分成几个表,用户表我们是记录用户的基础信息,包括手机、昵称、头像。而工人和员工各有各的表。那么就有一个问题,不同的角色…...
MySQL中【正则表达式】用法
MySQL 中正则表达式通过 REGEXP 或 RLIKE 操作符实现(两者等价),用于在 WHERE 子句中进行复杂的字符串模式匹配。以下是核心用法和示例: 一、基础语法 SELECT column_name FROM table_name WHERE column_name REGEXP pattern; …...
使用 SymPy 进行向量和矩阵的高级操作
在科学计算和工程领域,向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能,能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作,并通过具体…...
免费数学几何作图web平台
光锐软件免费数学工具,maths,数学制图,数学作图,几何作图,几何,AR开发,AR教育,增强现实,软件公司,XR,MR,VR,虚拟仿真,虚拟现实,混合现实,教育科技产品,职业模拟培训,高保真VR场景,结构互动课件,元宇宙http://xaglare.c…...
学习一下用鸿蒙DevEco Studio HarmonyOS5实现百度地图
在鸿蒙(HarmonyOS5)中集成百度地图,可以通过以下步骤和技术方案实现。结合鸿蒙的分布式能力和百度地图的API,可以构建跨设备的定位、导航和地图展示功能。 1. 鸿蒙环境准备 开发工具:下载安装 De…...
DBLP数据库是什么?
DBLP(Digital Bibliography & Library Project)Computer Science Bibliography是全球著名的计算机科学出版物的开放书目数据库。DBLP所收录的期刊和会议论文质量较高,数据库文献更新速度很快,很好地反映了国际计算机科学学术研…...


