C++学习第九天(list及其模拟实现)

1、list介绍

  • list是可以在常熟范围内任意位置进行 插入和删除的序列式容器,并且该容器可以前后双向迭代
  • list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素
  • list和forward_list非常相似,最主要不同的是forward_list是单链表,只能朝前迭代,以让其更简单高效。
  • list可以在任何位置进行插入,移除元素的效率更高
  • 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问。

 2、list的使用

list中的接口比较多,一下是常见的重要接口

list的构造

构造函数接口说明
list(size_type n,const value_type& val = value_type())构造list中包含n个值为val的元素
list()构造空的list
list(const list& x)拷贝构造函数
list(InputIterator first, InputIterator)用[first, last)区间中的元素构造list

list iterator的使用

函数声明接口说明
begin + end返回第一个元素迭代器+返回最后一个元素下一个位置的迭代器
rbegin + rend返回第一个元素的reverse_iterator,即end位置,返回最后一个元素的下一个位置的reverse_iterator,即begin位置

【ATT】

  • begin和end为正向迭代器,对迭代器执行++操作,迭代器向后移动
  • rbegin和rend为反向迭代器,对迭代器执行++操作,迭代器向前移动

list capacity的使用

函数声明接口说明
empty检测list是否为空,是返回true,否则返回false
size返回list中有效节点的个数

list element access的使用

函数声明借口说明
front返回list的第一个节点中值的引用
back返回list的最后一个节点中值的引用

list modifiers的使用

函数声明接口说明
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中的有效元素

list的迭代器失效(重点)

概念:迭代器失效即迭代器所指向的节点无效,即该节点被删除了,因为list的底层结构是带头节点的双向循环链表,因此在list中进行插入时是不会导致list的迭代器失效的,只有在删除的时候才会失效,而且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响

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

3、list的模拟实现

#pragma once
#include<iostream>
#include<assert.h>using namespace std;namespace bit
{//List节点类template<class T>struct ListNode{ListNode(const T& val = T()):_prev(nullptr),_next(nullptr),_val(val){}ListNode<T>* _prev;ListNode<T>* _next;T _val;};template<class T, class Ref, class Ptr>class ListIterator{typedef ListNode<T> Node;typedef ListIterator<T, Ref, Ptr> Self;public:typedef Ref Ref;typedef Ptr Ptr;public:ListIterator(Node* node = nullptr):_node(node){}//具有指针行为Ref operator*(){return _node->_val;}Ptr operator->(){return &(operator*());}//迭代器支持移动Self& operator++(){_node = _node->_next;return *this;}Self operator++(int){Self tmp(*this);_node = _node->_next;return tmp;}Self& operator--(){_node = _node->_prev;return *this;}Self& operator--(int){Self tmp(*this);_node = _node->_prev;return tmp;}//迭代器支持比较bool operator!=(const Self& l)const{return _node != l._node;}bool operator==(const Self& l)const{return _node != l._node;}Node* _node;};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 tmp(_it);--tmp;return *tmp;}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;};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;// 反向迭代器typedef ReverseListIterator<iterator> reverse_iterator;typedef ReverseListIterator<const_iterator> const_reverse_iterator;public:///// List的构造list(){CreateHead();}list(int n, const T& value = T()){CreateHead();for (int i = 0; i < n; ++i)push_back(value);}template <class Iterator>list(Iterator first, Iterator last){CreateHead();while (first != last){push_back(*first);++first;}}list(const list<T>& l){CreateHead();// 用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){// 有效元素个数减少到newsizewhile (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){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:void CreateHead(){_head = new Node;_head->_prev = _head;_head->_next = _head;}private:Node* _head;};
}///
// 对模拟实现的list进行测试
// 正向打印链表
template<class T>
void PrintList(const bite::list<T>& l)
{auto it = l.begin();while (it != l.end()){cout << *it << " ";++it;}cout << endl;
}// 测试List的构造
void TestBiteList1()
{bite::list<int> l1;bite::list<int> l2(10, 5);PrintList(l2);int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };bite::list<int> l3(array, array + sizeof(array) / sizeof(array[0]));PrintList(l3);bite::list<int> l4(l3);PrintList(l4);l1 = l4;PrintList(l1);
}// PushBack()/PopBack()/PushFront()/PopFront()
void TestBiteList2()
{// 测试PushBack与PopBackbite::list<int> l;l.push_back(1);l.push_back(2);l.push_back(3);PrintList(l);l.pop_back();l.pop_back();PrintList(l);l.pop_back();cout << l.size() << endl;// 测试PushFront与PopFrontl.push_front(1);l.push_front(2);l.push_front(3);PrintList(l);l.pop_front();l.pop_front();PrintList(l);l.pop_front();cout << l.size() << endl;
}// 测试insert和erase
void TestBiteList3()
{int array[] = { 1, 2, 3, 4, 5 };bite::list<int> l(array, array + sizeof(array) / sizeof(array[0]));auto pos = l.begin();l.insert(l.begin(), 0);PrintList(l);++pos;l.insert(pos, 2);PrintList(l);l.erase(l.begin());l.erase(pos);PrintList(l);// pos指向的节点已经被删除,pos迭代器失效cout << *pos << endl;auto it = l.begin();while (it != l.end()){it = l.erase(it);}cout << l.size() << endl;
}// 测试反向迭代器
void TestBiteList4()
{int array[] = { 1, 2, 3, 4, 5 };bite::list<int> l(array, array + sizeof(array) / sizeof(array[0]));auto rit = l.rbegin();while (rit != l.rend()){cout << *rit << " ";++rit;}cout << endl;const bite::list<int> cl(l);auto crit = l.rbegin();while (crit != l.rend()){cout << *crit << " ";++crit;}cout << endl;
}};
}

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

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

相关文章

nodejs 老生代和新生代如何理解

在Node.js中&#xff0c;虽然Node.js本身并不直接管理内存的具体分配与回收策略&#xff0c;但其底层依赖的JavaScript引擎V8确实实现了自动内存管理机制&#xff0c;其中包括了对内存区域的细分&#xff0c;其中就包括了“新生代”和“老生代”的概念。 新生代&#xff08;Yo…

学校开展第二届教学名师沙龙

四川城市职业学院讯 4月23日下午&#xff0c;党委教师工作部&#xff08;质量部&#xff09;、教师发展中心组织开展了以“大力弘扬教育家精神&#xff0c;建设高质量高水平教师队伍”为主题的第二届教学名师经验分享沙龙活动。全校12名入选学校教学名师&#xff08;名辅导员…

ubuntu 复制文件路径

前言 我打算搞一个ubuntu右键复制文件路径的插件&#xff0c;但是找不到&#xff0c;只能平替 这个配置&#xff0c;可以把文件拖拽到cmd窗口&#xff0c;然后就直接cmd输出文件路径 配置 cd ~ vim .bashrc 在文件结尾添加 cdd () { ddirname "$1"; echo …

Spring 注解开发详解

1. 注解驱动入门案例介绍 1.1 需求描述 1.需求&#xff1a;实现保存一条数据到数据库。 2.表结构&#xff1a;create table account(id int primary key auto_increment,name varchar(50),money double(7,2)); 3.要求&#xff1a;使用spring框架中的JdbcTemplate和DriverMana…

虚拟机VMware安装与Ubuntu

1.虚拟机安装 链接&#xff1a;百度网盘 请输入提取码 提取码&#xff1a;2fr6 CG54H-D8D0H-H8DHY-C6X7X-N2KG6 2.Ubuntu下载 Download Ubuntu Desktop | Ubuntu 3.设置 如后续要下一些软件越大越好

Chrome 侧边栏开发示例

前言 最近做项目&#xff0c;需要开发浏览器扩展&#xff0c;但是考虑页面布局兼容性问题&#xff0c;使用了Chrome114开始的侧边栏&#xff0c;浏览器自带的能力毕竟不会出现兼容性问题&#xff0c;不过Chrome123开始&#xff0c;侧边栏居然又可以选择固定右侧扩展栏了&#…

【黑马头条】-day11热点文章实时计算-kafka-kafkaStream-Redis

文章目录 今日内容1 实时流式计算1.1 应用场景1.2 技术方案选型 2 Kafka Stream2.1 概述2.2 KafkaStream2.3 入门demo2.3.1 需求分析2.3.2 实现2.3.2.1 添加依赖2.3.2.2 创建快速启动&#xff0c;生成kafka流2.3.2.3 修改生产者2.3.2.4 修改消费者2.3.2.5 测试 2.4 SpringBoot集…

光伏无人机巡检主要有些什么功能和特点?

随着科技的飞速发展&#xff0c;无人机技术已经渗透到多个行业领域&#xff0c;光伏产业便是其中之一。光伏无人机巡检&#xff0c;作为一种新兴的巡检方式&#xff0c;正在逐渐取代传统的人工巡检&#xff0c;为光伏电站的安全、高效运行提供了有力保障。那么&#xff0c;光伏…

记录ubuntu20.04安装nvidia-525.85.05显卡驱动(学习笔记2024.4.15、4.16)

电脑&#xff1a;华硕天选X2024 显卡&#xff1a;4060Ti i5-14400F 架构&#xff1a;x86_64 我需要使用Linux系统使用IsaacSim进行仿真&#xff0c;所以安装的都是IsaacSim中的推荐版本。 一.对新鲜的电脑进行分盘 电脑刚到手&#xff0c;900多个G全在C盘里&#xff0c;给它…

【C语言__联合和枚举__复习篇10】

目录 前言 一、联合体 1.1 联合体的概念 1.2 联合体与结构体关于声明和内存布局的比较 1.3 联合体的大小如何计算 1.4 使用联合体的2个示例 二、枚举体 2.2 枚举体的概念 2.2 枚举体的优点 前言 本篇主要讨论以下问题&#xff1a; 1. 联合体是什么&#xff0c;它有什么特点 …

如何通过ABAP将数据写回BPC模型

今天给大家安利一个标准方法&#xff0c;主要用于回写BPC模型数据&#xff0c;一般情况下&#xff0c;BPC模型数据的回写&#xff0c;标准的方式有数据抽取&#xff0c;直接抽取供数模型的数&#xff0c;利用BW标准转换方式进行供数&#xff0c;又或者通过逻辑脚本BADI的方式直…

Python之PCV库安装教程以及解说

PCV库是一个比较古老的python库 在网上参考了很多教程 于是现在想要总结一下,并且分享整理了一下资源 很多人是通过pycharm内部直接下载PCV 但是导入时还要报错 因为PCV版本不对 pycharm自动下载的版本过于旧 是0.0.2 而我们需要的是1.0.0版本 否则下面PCV部分会报错无法导入…

LeetCode - LCR 179.查找总价格为目标值的两个商品

一. 题目链接 LeetCode - LCR 179. 查找总价格为目标值的两个商品 解法&#xff08;双指针 - 对撞指针&#xff09;&#xff1a; 算法思路&#xff1a; 注意到本题是升序的数组&#xff0c;因此可以用「对撞指针」优化时间复杂度。 算法流程&#xff1a; 初始化left &#…

如何快速申请SSL证书实现HTTPS访问?

申请SSL证书最简单的方法通常涉及以下几个步骤&#xff0c;尽量简化了操作流程和所需专业知识&#xff1a; 步骤一&#xff1a;选择适合的SSL证书类型 根据您的网站需求&#xff0c;选择最基础的域名验证型&#xff08;DV SSL&#xff09;证书&#xff0c;它通常只需验证域名所…

【以奖代补】诗情画意润童心 书香课堂志愿行

中华古诗词历史源远流长&#xff0c;名篇佳作数不胜数。为弘扬民族文化精髓&#xff0c;丰富乡村儿童假期生活。2024年4月21日上午&#xff0c;襄州区社会工作者协会联合襄州区张家集镇社工站、张集村“童叟乐园”志愿服务队在张集村开展“诗情画意润童心 书香课堂志愿行”志愿…

JavaSE:抽象

一&#xff0c;抽象是什么&#xff0c;抽象和面向对象有什么关系 抽象&#xff0c;个人理解&#xff0c;就是抽象的意思 我们都知道面向对象的四大特征&#xff1a;封装&#xff0c;继承&#xff0c;多态&#xff0c;抽象 为什么抽象是面向对象的特征之一&#xff0c;抽象和面…

【ESP32入门实战】初识ESP32

【ESP32入门实战】初识ESP32 文章目录 【ESP32入门实战】初识ESP32&#x1f468;‍&#x1f3eb;前言【写作缘由】&#x1f9d1;‍&#x1f393;ESP32介绍&#x1f469;‍&#x1f4bb;ESP32-WROOM-32&#x1f469;‍&#x1f4bb;ESP32的组成部分 &#x1f468;‍&#x1f3eb…

记内网http洪水攻击,导致网页无法访问一事

事由 最近两日&#xff0c;部分同事在访问税纪云平台时&#xff0c;登录跳转页面频繁转圈、要么就是出现无法连接的错误提示。 无法访问此页面 已重置连接。 请尝试: 检查连接检查代理和防火墙运行 Windows 网络诊断经过以下几方面的排查&#xff0c;无果。 后续通过检查…

4月23号总结

java实现发送邮件 在做聊天室项目的时候&#xff0c;由于需要发送邮箱验证码&#xff0c;所以自己查找了这方面的内容。 首先需要在Maven里面依赖 <dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><versio…

冯喜运:4.25黄金原油上演过山车走势附操作建议

【黄金消息面分析】&#xff1a;周四&#xff08;4月25日&#xff09;亚洲时段&#xff0c;现货黄金窄幅震荡&#xff0c;目前交投于2320美元/盎司附近。金价周三企稳在2300关口上方&#xff0c;收报2315.80美元/盎司&#xff0c;中东紧张局势导致的风险溢价有所缓和&#xff0…