【C++】STL — List的接口讲解 +详细模拟实现

news2024/10/5 17:15:52

前言:
本章我们将学习STL中另一个重要的类模板list…

  • list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
  • list的底层是带头双向循环链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
  • list与forward_list非常相似:主要区别在于forward_list对象是单链接列表,因此它们只能向前迭代,以换取更小、更高效。
  • 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好。
  • 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,需要线性的时间开销。

list是带哨兵位头节点的双向循环链表,
在list中进行插入节点不会导致list的迭代器失效,
只有删除节点时才会出现失效问题,并且失效的只是指向被删除节点的迭代器,会有野指针问题,其他迭代器不受影响

目录

    • 1. list的使用
      • 1.1 list的初始化 + 迭代器的使用
      • 1.2 对list的排序
    • 2. list的模拟实现(list.h)
      • 2.1 链表结点的申请:
      • 2.2 用类封装List 的迭代器
      • 2.3 List链表的实现
      • 2.4 迭代器失效的问题

1. list的使用

我们学习的STL中的list是一种:带头双向循环链表。(带有哨兵位头结点的)

  • 带头双向循环链表 – 链表中的最优设计
  • 可以实现任意位置〇(1)的插入删除,只需要改前后的关系

1.1 list的初始化 + 迭代器的使用

在我们使用list之前我们需要先包一下头文件#include< list >
在这里插入图片描述

#include <iostream>
#include <list>

int main ()
{
  // constructors used in the same order as described above:
  std::list<int> first;                                // empty list of ints
  std::list<int> second (4,100);                       // four ints with value 100
  std::list<int> third (second.begin(),second.end());  // iterating through second
  std::list<int> fourth (third);                       // a copy of third

  // the iterator constructor can also be used to construct from arrays:
  int myints[] = {16,2,77,29};
  std::list<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
  return 0;
}

1.2 对list的排序

对于一般的容器而言,我们包一个算法库 #incldue < alogrithm > 可以对普通的容器进行排序。

void test_list2()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(4);
	v.push_back(2);
	v.push_back(4);
	v.push_back(3);
	sort(v.begin(), v.end());
	
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;

	list<int> lt;
	lt.push_back(1);
	lt.push_back(4);
	lt.push_back(2);
	lt.push_back(4);
	lt.push_back(3);
	lt.sort();
	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
}
  • 像vector和string而言,这种连续的容器可以直接用库中的sort
  • 而对于list而言和之前的顺序容器有所区别,因为其链式结构,库中的算法不支持
  • list单独实现了一个自己的排序
  • 但是list的排序效率很低
    在这里插入图片描述

注意:
可见把list的数据拷贝到vector中再,用sort算法对vector中排序,再将vector中的数据拷贝到list中都比直接用list排序要快,所以list的排序效率很低。

2. list的模拟实现(list.h)

在这里插入图片描述

2.1 链表结点的申请:

namespace Joker
{
    //list的节点类
	template<class T>
	struct list_node
	{
		list_node<T>* _next;
		list_node<T>* _prev;
		T _data;

		list_node(const T& val = T())
			:_next(nullptr)
			, _prev(nullptr)
			, _data(val)
		{}
	};

注意:

- 默认生成的析构函数够用。

2.2 用类封装List 的迭代器

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

    1. 原生态指针,比如:vector
    1. 将原生态指针进行封装,因迭代器使用形式与指针完全相同,因此在自定义的类中必须实现以下方法:
      1. 指针可以解引用,迭代器的类中必须重载operator*()
      2. 指针可以通过->访问其所指空间成员,迭代器类中必须重载oprator->()
      3. 指针可以++向后移动,迭代器类中必须重载operator++()与operator++(int)
        至于operator–()/operator–(int)释放需要重载,根据具体的结构来抉择,双向链表可以向前 移动,所以需要重载,如果是forward_list就不需要重载–
      4. 迭代器需要进行是否相等的比较,因此还需要重载operator==()与operator!=()
   template<class T, class Ref, class Ptr>
	class ListIterator
	{
		typedef ListNode<T> Node;
		typedef ListIterator<T, Ref, Ptr>Self;

     public:
         // 构造
		ListIterator(Node* node = nullptr)
			: _node(node)
		{}
      // 具有指针类似行为
		Ref operator*() 
		{ 
			return _node->_data;
		}

		Ptr operator->() 
		{ 
			//return &(operator*()); 
			return &_node->_data;
		}	//
		// 迭代器支持移动
		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		Self operator++(int)
		{
			Self temp(*this);
			_node = _node->_next;
			return temp;
		}
         //--it
		Self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}
        //it--
		Self operator--(int)
		{
			Self temp(*this);
			_node = _node->_prev;
			return temp;
		}
//
		// 迭代器支持比较
		bool operator!=(const Self& l)const
		{ 
			return _node != l._node;
		}

		bool operator==(const Self& l)const
		{ 
			return _node != l._node;
		}
		Node* _node;
	};

注意:

  • 析构函数(不需要写)-- 节点不属于迭代器,不需要迭代器释放

  • 编译器生成的默认析构函数够用,对内置类型不敢处理,只对自定义类型处理

  • 拷贝构造和赋值重载(不需要写)

  • 默认生成的浅拷贝就可以

(2)运算符重载 - > :

Ptr operator->() 
	{
		//return &(operator*());0
		return &_node->_data;
	}
	返回的是一个指针。

优化如下

  • it.operator->() – 返回类型是AA*的迭代器
  • it.operator->() ->_data;
  • 编译器为了可读性进行了优化处理
  • 如果不优化应该是it->->_data;
  • 优化以后,省略了一个->

2.3 List链表的实现

template<class T>
class list
	{
		typedef ListNode<T> Node;
	public:
		// 正向迭代器
		typedef ListIterator<T, T&, T*> iterator;
		typedef ListIterator<T, const T&, const T&> const_iterator;

		// List的构造
		list()
		{
			_head = new Node();
			_head->_next = _head;
			_head->_prev = _head;
		}

		list(int n, const T& value = T())
		{
			empty_init();
			for (int i = 0; i < n; ++i)
				push_back(value);
		}

      //创造一个哨兵位头结点出来,通用
		void empty_init()
		{
			_head = new Node();
			_head->_next = _head;
			_head->_prev = _head;
		}
		
		template <class Iterator(大写I)>
		list(Iterator first, Iterator last)
		{
			empty_init();
			while (first != last)
			{
				push_back(*first);
				++first;
			}
		}
//拷贝构造现代写法:--需要使用深拷贝
		list(const list<T>& l)
		{
		 //创造一个哨兵位头节点出来,不初始化就是随机值
			empty_init();
		// 用l中的元素构造临时的temp,然后与当前对象交换
			list<T> temp(l.begin(), l.end());
			this->swap(temp);
		}
		list<T>& operator=(list<T> l)
		{
			this->swap(l);
			return *this;
		}

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

		///
		// List的迭代器
		iterator begin() 
		{ 
			return iterator(_head->_next); 
		}

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

		const_iterator begin()const 
		{ 
			return const_iterator(_head->_next); 
		}

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

		reverse_iterator rbegin()
		{
			return reverse_iterator(end());
		}

		reverse_iterator rend()
		{
			return reverse_iterator(begin());
		}

		const_reverse_iterator rbegin()const
		{
			return const_reverse_iterator(end());
		}

		const_reverse_iterator rend()const
		{
			return const_reverse_iterator(begin());
		}

		///
		// List的容量相关
		size_t size()const
		{
			Node* cur = _head->_next;
			size_t count = 0;
			while (cur != _head)
			{
				count++;
				cur = cur->_next;
			}

			return count;
		}

		bool empty()const
		{
			return _head->_next == _head;
		}

		void resize(size_t newsize, const T& data = T())
		{
			size_t oldsize = size();
			if (newsize <= oldsize)
			{
				// 有效元素个数减少到newsize
				while (newsize < oldsize)
				{
					pop_back();
					oldsize--;
				}
			}
			else
			{
				while (oldsize < newsize)
				{
					push_back(data);
					oldsize++;
				}
			}
		}
		
		// List的元素访问操作
		// 注意:List不支持operator[]
		T& front()
		{
			return _head->_next->_val;
		}

		const T& front()const
		{
			return _head->_next->_val;
		}

		T& back()
		{
			return _head->_prev->_val;
		}

		const T& back()const
		{
			return _head->_prev->_val;
		}

		
		// List的插入和删除
		void push_back(const T& val) 
		{ 
		//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(), val); 
		}

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

		void push_front(const T& val) 
		{ 
			insert(begin(), val); 
		}

		void pop_front() 
		{ 
			erase(begin()); 
		}

		// 在pos位置前插入值为val的节点
		iterator insert(iterator pos, const T& val)
		{
			Node* pNewNode = new Node(val);
			Node* pCur = pos._node;
			// 先将新节点插入
			pNewNode->_prev = pCur->_prev;
			pNewNode->_next = pCur;
			pNewNode->_prev->_next = pNewNode;
			pCur->_prev = pNewNode;
			return iterator(pNewNode);
		}

		// 删除pos位置的节点,返回该节点的下一个位置
		iterator erase(iterator pos)
		{
			// 找到待删除的节点
			Node* pDel = pos._node;
			Node* pRet = pDel->_next;

			// 将该节点从链表中拆下来并删除
			pDel->_prev->_next = pDel->_next;
			pDel->_next->_prev = pDel->_prev;
			delete pDel;

			return iterator(pRet);
		}

		void clear()
		{
			Node* cur = _head->_next;
			// 采用头删除删除
			while (cur != _head)
			{
				_head->_next = cur->_next;
				delete cur;
				cur = _head->_next;
			}

			_head->_next = _head->_prev = _head;
		}

		void swap(bite::list<T>& l)
		{
			std::swap(_head, l._head);
		}
	private:
		Node* _head;
	};
}

2.4 迭代器失效的问题

  • list insert迭代器不失效,不存在野指针的问题,也不存在意义变了的问题
  • list erase(it)以后,迭代器是会失效的,是野指针问题

解决办法:

  • 之前vector容器迭代器失效时解决办法一样,使用返回值接收。

尾声
看到这里,相信大家对这个C++有了解了。
如果你感觉这篇博客对你有帮助,不要忘了一键三连哦

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

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

相关文章

从零到屎山系列-游戏开发(Day2)

简介 这次就来一个比较简单的小游戏贪吃蛇 贪吃蛇 游戏规则就是一串珠子不断的移动&#xff0c;碰到场景里面的食物变长一点&#xff0c;碰到墙壁游戏结束。 开始动手 设计绘制设备 首先我计划从一个控制台游戏开始&#xff0c;需要一个控制台下的绘图机制&#xff0c;希…

基于Sen+MK的多站点不同季节和年尺度的SPEI趋势分析.md

再大的风浪&#xff0c;不过只短暂喧哗。 文章目录 前言1. 概述2.1 问题情景2.2 说明 2. 版本2.1 天津&#xff0c;2024年5月4日&#xff0c;Version1 3. 微信公众号GISRSGeography 一、数据1. 输入数据2. 输出数据 二、程序代码三、参考资料 前言 1. 概述 2.1 问题情景 假…

java-Spring-mvc-(请求和响应)

目录 &#x1f4cc;HTTP协议 超文本传输协议 请求 Request 响应 Response &#x1f3a8;请求方法 GET请求 POST请求 &#x1f4cc;HTTP协议 超文本传输协议 HTTP协议是浏览器与服务器通讯的应用层协议&#xff0c;规定了浏览器与服务器之间的交互规则以及交互数据的格式…

thinkphp6 workerman无法使用框架Db/model等类库方法解决方案

thinkphp6 workerman无法使用框架Db/model相关操作解决 执行安装相关扩展 composer require webman/gateway-worker引入成功后编辑服务类文件,直接展示代码 <?phpnamespace app\server\controller;use GatewayWorker\BusinessWorker; use GatewayWorker\Gateway; use Gate…

java异常.day30(Error,Exception)

Error和Exception说明 Error Error类及其子类表示的是Java虚拟机&#xff08;JVM&#xff09;无法或不应该尝试恢复的严重问题。这些问题通常是由JVM本身的问题、系统资源耗尽、或其他不可控的环境因素引起的。由于Error是不可恢复的&#xff0c;因此应用程序不应该尝试捕获和…

Cisco WLC 2504控制器重启后所有AP掉线故障-系统日期时间

1 故障描述 现场1台WLC 2504控制器掉电重启后&#xff0c;所有AP均无线上线&#xff0c; 正常时共有18个AP在线&#xff0c;而当前为0 AP在线数量为0 (Cisco Controller) >show ap sumNumber of APs.................................... 0Global AP User Name..........…

细胞自动机与森林火灾与燃烧模拟

基于 元胞自动机-森林火灾模拟_vonneumann邻域-CSDN博客 进行略微修改&#xff0c;解决固定方向着火问题&#xff0c;用了一个meshv2数组记录下一状态&#xff0c;避免旧状态重叠数据失效。 参数调整 澳洲森林火灾蔓延数学建模&#xff0c;基于元胞自动机模拟多模式下火灾蔓延…

大语言模型从Scaling Laws到MoE

1、摩尔定律和伸缩法则 摩尔定律&#xff08;Moores law&#xff09;是由英特尔&#xff08;Intel&#xff09;创始人之一戈登摩尔提出的。其内容为&#xff1a;集成电路上可容纳的晶体管数目&#xff0c;约每隔两年便会增加一倍&#xff1b;而经常被引用的“18个月”&#xf…

【C++题解】1659. 是否含有数字5

问题&#xff1a;1659. 是否含有数字5 类型&#xff1a;分支结构 题目描述&#xff1a; 请从键盘读入一个五位整数 n&#xff0c;判断其是否含有数字 5&#xff0c;如果含有数字 5 &#xff0c;请输出这个 5 位数各个位的和&#xff1b;如果不含数字 5 &#xff0c;请直接输出…

IoTDB 入门教程 基础篇⑧——数据库管理工具 | IDEA 连接 IoTDB

文章目录 一、前文二、下载iotdb-jdbc三、IDEA驱动四、IDEA连接数据库五、数据库应用六、其他 一、前文 IoTDB入门教程——导读 二、下载iotdb-jdbc 下载地址org/apache/iotdb/iotdb-jdbc&#xff1a;https://maven.proxy.ustclug.org/maven2/org/apache/iotdb/iotdb-jdbc/ 本…

记录vue报错问题 in ./node_modules/axios/lib/platform/index.js

今天这个问题困扰了我许久 报错内容如下&#xff1a; 最初一直以为是我没装axios&#xff0c;又重新装了一次&#xff0c;后面才发现是axios版本原因&#xff0c;真的总是被版本的原因困住真的很烦 解决方法如下&#xff1a; 将axios的版本改为1.5.0 1、打开项目的文件夹“…

探索LLM在广告领域的应用——大语言模型的新商业模式和新个性化广告的潜力

概述 在网络搜索引擎的领域中&#xff0c;广告不仅仅是一个补充元素&#xff0c;而是构成了数字体验的核心部分。随着互联网经济的蓬勃发展&#xff0c;广告市场的规模已经达到了数万亿美元&#xff0c;并且还在持续扩张。广告的经济价值不断上升&#xff0c;它已经成为支撑大…

C++奇迹之旅:STL初步学习

文章目录 &#x1f4dd;什么是STL&#x1f320; STL的版本&#x1f309;STL的六大组件 &#x1f320;STL的重要性&#x1f309;如何学习STL&#x1f320;STL的缺陷&#x1f6a9;总结 &#x1f4dd;什么是STL STL(standard template libaray-标准模板库)&#xff1a;是C标准库的…

ubuntu安装LVGL/lv_img_conv并在thinkphp中进行调用生成bin文件

项目需求&#xff1a;需要处理图片成为bin文件&#xff0c;并以二进制的方式传给蓝牙设备&#xff0c;当前仅介绍如何安装&#xff0c;对lvgl功能和简介不做过多描述 项目库地址&#xff1a;https://github.com/lvgl/lv_img_conv 安装过程比较简单 一&#xff0c;确保node.j…

ubuntu20中ros与anaconda的python版本冲突问题

系统环境 原本系统是ubuntu20 noetic&#xff0c;python都在/usr/bin中&#xff0c;一共是两个版本的python&#xff0c;一个是python3.8&#xff0c;另一个是python2.7。 问题发现 当安装anaconda后&#xff0c;并且将anaconda的bin目录加入到系统环境中时候&#xff0c;…

Unity 性能优化之动态批处理(四)

提示&#xff1a;仅供参考&#xff0c;有误之处&#xff0c;麻烦大佬指出&#xff0c;不胜感激&#xff01; 文章目录 前言一、动态合批是什么&#xff1f;二、使用动态批处理1.打开动态合批2.满足条件 三、检查动态合批是否成功五、动态合批弊端总结 前言 动态批处理是常用优…

《QT实用小工具·五十四》果冻弹出效果的动画按钮

1、概述 源码放在文章末尾 该项目实现动画按钮&#xff0c;鼠标放在按钮上可以弹性拉出的三个按钮&#xff0c;使用贝塞尔曲线实现&#xff0c;项目demo显示如下所示&#xff1a; 项目部分代码如下所示&#xff1a; #ifndef WATERCIRCLEBUTTON_H #define WATERCIRCLEBUTTON…

TOOL使用fiddler导出的har文件导入到postman测试接口

在fiddler操作 export → File → Export Sessions → alls-->http arch v1.1 导出的har文件直接拖入到浏览器的调试工具中&#xff0c; 然后复制为curl&#xff0c;导入到postman中即可&#xff01;

菜鸡学习netty源码(四)—— EventLoop

1.概述 我们前面进行过分析,channel为netty网络操作的抽象类,EventLoop负责处理注册到其上的Channel处理的I/O事件;EventLoopGroup是一个EventLoop的分组,它可以获取到一个或者多个的EventLoop对象。 2.类关系图 NioEventLoopGroup的类继承图,蓝色部分为对应的java类,绿…

IoTDB 入门教程 基础篇⑦——数据库管理工具 | DBeaver 连接 IoTDB

文章目录 一、前文二、下载iotdb-jdbc三、安装DBeaver3.1 DBeaver 下载3.2 DBeaver 安装 四、安装驱动五、连接数据库六、参考 一、前文 IoTDB入门教程——导读 二、下载iotdb-jdbc 下载地址org/apache/iotdb/iotdb-jdbc&#xff1a;https://maven.proxy.ustclug.org/maven2/o…