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位置

【注意】
1. begin与end为正向迭代器,对迭代器执行++操作,迭代器向后移动
2. rbegin(end)与rend(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,否则返回false
size                                                                  返回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 != &lt) {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的迭代器失效

迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致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;
}

四、listvector的对比

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

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

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

相关文章

HDFS 分布式存储 spark storm HBase

HDFS 分布式存储 spark storm HBase 分布式结构 master slave name node client 负责文件的拆分 128MB 3份 data node MapReduce 分布式计算 离线计算 2.X之前 速度比较慢 对比spark 编程思想 Map 分 Reduce 合 hadoop streaming Mrjob Yarn 资源管理 cpu 内存 MapReduc…

NoSQL———Redis配置与优化

目录 一、关系数据库与非关系型数据库 1.1 关系型数据库 1.2 非关系型数据库 1.3 关系型数据库和非关系型数据库区别 1.3.1 非关系型数据库产生背景 二、Redis简介 2.1 redis优点&#xff1a; 三、Redis 安装部署 四、Redis 命令工具 4.1 redis-cli 命令行工具 …

vue3代码编辑器组件codemirror-editor-vue3

官方文档&#xff1a;https://github.com/RennCheung/codemirror-editor-vue3 国内镜像&#xff1a;https://renncheung.github.io/codemirror-editor-vue3/zh-CN/guide/getting-started 1.安装 npm install codemirror-editor-vue3 codemirror5.x -S2.代码示例 <templat…

mybatis框架遇到的问题:All elements are null

今天在做一个查询接口&#xff0c;应用场景是统计选择日期范围内的每日数据量&#xff0c;于是便想到了使用count&#xff08;&#xff09;函数来统计总行数来代表数据量&#xff0c;并且以记录时间的字段来作为分组标准&#xff08;group by&#xff09;&#xff0c;大体思路有…

基于ssm+mysql+jsp高校疫情防控出入信息管理系统

基于ssmmysqljsp高校疫情防控出入信息管理系统 一、系统介绍二、功能展示1.登陆2.教师管理3.学生管理4.打卡记录管理5.学生申请通行证6.通行证管理7.留言信息管理8.公告类型管理9.公告管理 四、获取源码 一、系统介绍 学生 : 个人中心、打卡记录管理、学生申请通行证、通行证管…

Delphi XE的原生JSONObject如何判断键值是否存在?

【问题现象】 Delphi XE的原生JSONObject&#xff0c;取出键值的时候如下&#xff1a; //json是传入的参数&#xff0c;里面包括"food_name"等之类的键值&#xff0c;没有food_type键值 procedure XXXXFunciton(json:TJSONObject) var strFoodName,strFoodType:S…

<C++> STL_string

目录 1.string类 2.string类的接口 2.1 成员函数 2.1.1 string构造函数 2.1.2 string赋值运算 2.1.3 string析构函数 2.2 string对象访问以及迭代器 2.2.1 string的遍历方式 2.2.2 迭代器的使用 2.2.3 const_迭代器的使用 2.2.4 at 2.2.5 back和front 2.3 string容…

Docker基础命令(一)

Docker使用1 一、运行终端 打开终端&#xff0c;输入docker images &#xff0c;如果运行正常&#xff0c;表示docker已经可以在本电脑上使用了 二、docker常用命令 指令说明docker images查看已下载的镜像docker rmi 镜像名称:标签名删除已下载的镜像docker search 镜像从官…

ffmpeg 的帮助系统

----------------------------------------------- author: hjjdebug date: 2023年 07月 31日 星期一 14:32:15 CST ffmpeg 的帮助系统 目的: 搞清楚它都打印了什么? 它是怎样实现的. ----------------------------------------------- $ffprobe -h 1996行输出 $ffmpeg -h…

Java如何实现将类文件打包为jar包

目录 将类文件打包为jar包 1.写类文件2.编译3.测试4.打jar包jar包应该怎么打&#xff1f; 1.首先确保你的项目2.选中你的项目,点右键3.选择runnable jar file4.如下图,直接看图5.然后点finish 将类文件打包为jar包 为实际项目写了一个工具类&#xff0c;但是每次使用时都需要…

xcode中如何显示文件后缀

xcode14.3 用不惯mac电脑真恶心&#xff0c;改个显示文件后缀找半天 1、首先双击打开xcode软件 2、此时&#xff0c;电脑左上角出现xcode字样(左上角如果看不到xcode字样&#xff0c;再次点击xcode软件弹出来就有了)&#xff0c;鼠标右键它&#xff0c;点击setting或者Prefere…

阿里云SLB负载均衡ALB、CLB和NLB有什么区别?

阿里云负载均衡SLB分为传统型负载均衡CLB&#xff08;原SLB&#xff09;、应用型负载均衡ALB和网络型负载均衡NLB&#xff0c;三者有什么区别&#xff1f;CLB是之前的传统的SLB&#xff0c;基于物理机架构的4层负载均衡&#xff1b;ALB是应用型负载均衡&#xff0c;7层负载均衡…

安卓音视频多对多级联转发渲染

最近利用自己以前学习和用到的音视频知识和工程技能做了一个android的sdk,实现了本地流媒体ipc rtsp 拉流以及自带mip usb等camera audio节点产生的流媒体通过webrtc sfu的方式进行多对多级联发布共享,网状结构&#xff0c;p2p组网&#xff0c;支持实时渲染以及转推rtmp&#x…

我的第一个前端(VS code ,Node , lite-server简易服务器,npm 运行)

第一种方式&#xff1a;使用Visual Studio Code创建并运行 第一个前端项目的步骤&#xff0c;如下&#xff1a; 1. 下载和安装Visual Studio Code&#xff1a; 访问Visual Studio Code官方网站&#xff08;Visual Studio Code - Code Editing. Redefined&#xff09;并根据你…

Java类的加载过程是什么?

本文重点 本文将学习类的加载过程,java命令将class文件放到类加载器中,那么之后经历了什么?本文将对其进行学习。 类加载方式? 两种加载方式:隐式加载(静态加载)和显式加载(动态加载) 隐式加载指的是在程序使用new等方式创建对象的时候,会隐式地调用类的加载器把…

【Docker】Docker的优势、与虚拟机技术的区别、三个重要概念和架构及工作原理详细讲解

前言 Docker 是一个开源的应用容器引擎&#xff0c;让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux或Windows操作系统的机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口。 作者简介&#xff1a; 辭七七&#xf…

GDAL C++ API 学习之路 OGRGeometry 环类 OGRLinearRing

OGRLinearRing class <ogrsf_frmts.h> OGRLinearRing 是 OGR 库中的一个类&#xff0c;它是一个线性环&#xff08;Linear Ring&#xff09;的几何对象&#xff0c;用于表示封闭的线性路径。线性环是由一系列连续的线段组成&#xff0c;首尾相连形成闭合的环。线…

驶向专业:嵌入式开发在自动驾驶中的学习之道

导语: 自动驾驶技术在汽车行业中的快速发展为嵌入式开发领域带来了巨大的机遇。作为自动驾驶的核心组成部分&#xff0c;嵌入式开发在驱动汽车的智能化和自主性方面发挥着至关重要的作用。本文将探讨嵌入式开发的学习方向、途径以及未来在自动驾驶领域中的展望。 一、学习方向:…

Java 解析Excel单元格的富文本

1. 总体介绍 该方法是解析 xlsx 单元格中的富文本&#xff0c;注意不是 xls&#xff0c;xls 的 api 不一样&#xff0c;试了很久没成功。只实现了解析 斜体字、上下标&#xff0c;其它的实现方式应该类似。 2. 具体实现 2.1 代码 package util;import java.io.FileInputStr…

人工智能安全-3-噪声数据处理

0 提纲 噪声相关概述噪声处理的理论与方法基于数据清洗的噪声过滤主动式过滤噪声鲁棒模型1 噪声相关概述 噪声类型: 属性噪声:样本中某个属性的值存在噪声标签噪声:样本归属类别关于噪声分布的假设:均匀分布、高斯分布、泊松分布等。 标签噪声的产生原因: (1)特定类别…