C++ stl容器list的底层模拟实现

目录

前言:

1.创建节点

2.普通迭代器的封装

3.反向迭代器的封装

为什么要对正向迭代器进行封装?

4.const迭代器

5.构造函数

6.拷贝构造

7.赋值重载

8.insert

9.erase

10.析构

11.头插头删,尾插尾删

12.完整代码+简单测试

总结:


前言:

模拟实现list,本篇的重点就是由于list是一个双向循环链表结构,所以我们对迭代器的实现不能是简单的指针的++,--了,因为我们知道,链表的存储不一定是连续的,所以直接++,--是链接不起来节点的,所以我们要对迭代器也就是对节点的指针进行封装。结尾会附上完整的代码。

1.创建节点

	template<class T>struct list_node{list_node<T>* _prev;list_node<T>* _next;T _data;list_node(const T& x= T())//这里不给缺省值可能会因为没有默认构造函数而编不过:_prev(nullptr),_next(nullptr),_data(x){}};

注意给缺省值,这样全缺省就会被当做默认构造了,不会因为没有默认构造而报错。

我们实现的list是带哨兵位的,它同时是迭代器的end()(因为是双向循环的list)。

 

2.普通迭代器的封装

	template<class T,class Ref,class Ptr>struct _list_iterator{typedef list_node<T> node;typedef _list_iterator<T, Ref, Ptr> self;node* _node;//对迭代器也就是节点的指针进行封装,因为list迭代器是不能直接++的_list_iterator(node* n):_node(n){}Ref operator*()//返回的必须是引用,不然改变不了外面的对象的成员,要支持对自己解引用改变值就要用应用{return _node->_data;}Ptr operator->(){return &(_node->_data);//返回地址,再解引用直接访问数据}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& s){return _node != s._node;}bool operator==(const self& s){return _node == s._node;}};

注意list是双向迭代器,可以++,--,不能+,-

这里对迭代器的实现就如我们开始所说的, 迭代器的实现就是使用节点的指针实现的,而我们不能直接对list创建出的节点进行++,--,所以要进行一层封装;然后再对节点指针初始化。

重载解引用时要注意返回的是引用,不然对自己解引用的时候,返回值如果是临时的,是改变不了内部的data的。

对于箭头的解引用,是为了支持这样的场景:

struct AA{int _a1;int _a2;AA(int a1=0,int a2=0):_a1(a1),_a2(a2){}};void test_list2(){list<AA> lt;lt.push_back(AA(1,1));lt.push_back(AA(2, 2));lt.push_back(AA(3, 3));list<AA>::iterator it = lt.begin();while (it != lt.end()){//cout << (*it)._a1 << " "<<(*it)._a2<<endl;cout << it->_a1 << " " << it->_a2 << endl;//面对这样的类型,需要重载->,.也可以访问,但是有点别扭++it;}cout << endl;}

迭代器遇到箭头,返回对象的地址也就是节点数据的地址,再解引用找到成员。或者说node中的data就是存放的是对象(也就是用来初始化的数据),然后重载的->拿到对象的地址,再->去访问里面的成员变量_a1。

对于前置后置++与--,前置就返回对象的引用,是传引用返回;后置需要进行拷贝给一个临时的对象,再对调用对象++--,返回的是tmp也就是没有改变的对象,是传值返回。注意区分前置后置,后置要加上参数int。

3.反向迭代器的封装

namespace my_iterator
{template<class Iterator,class Ref,class Ptr>struct ReverseIterator{typedef ReverseIterator<Iterator,Ref,Ptr> self;Iterator _cur;ReverseIterator(Iterator it):_cur(it){}Ref operator*(){Iterator tmp = _cur;//因为要--,而解引用是不能改值的,所以用tmp改并返回--tmp;return *tmp;}Ptr operator->(){return &operator*();//&this->operator*()}self operator++(){--_cur;//直接的++--就能直接改了,所以可以直接返回原对象,--(this->_cur)return *this;}self operator--(){++_cur;return *this;}bool operator!=(const self& s){return _cur != s._cur;}};
}

第一个模版参数就是任意类型的迭代器区间,因为我们实现反向迭代器需要现有正向迭代器。

一样的不能直接++--,所以进行一层封装,此时_cur就指向传的迭代器的位置。

对解引用的重载一样是要返回引用,不然返回的是一个临时的变量对自己解引用就没用了,也只有返回的是引用才能修改。例如我们要传的是begin(),那反向迭代器就应该从哨兵位开始,所以要先对传过来的迭代器进行--。

箭头就是返回当前位置迭代器的地址,所以是直接复用上面的。

++--与正向的迭代器相反,而_cur的类型就是传过来的迭代器类型,++--会调用传过来迭代器类型的重载。

 

为什么要对正向迭代器进行封装?

4.const迭代器

	typedef list_node<T> node;
public:typedef _list_iterator<T, T&, T*> iterator;typedef _list_iterator<T, const T&, const T*> const_iterator;typedef ReverseIterator<iterator,T&,T*> reverse_iterator;typedef ReverseIterator<iterator, const T&, const T*> const_reverse_iterator;const_iterator begin() const//本身const迭代器是让迭代器指向的内容不能修改,但是这样用const修饰迭代器本身也不能修改了{return const_iterator(_head->_next);}const_iterator end() const{return const_iterator(_head);}

 提供const版本,供const修饰的对象调用,防止权限的放大。

那为什么提供完const版本了,const版本已经可以供普通迭代器与const迭代器使用,还单独提出来这个版本?和因为const迭代器还需要迭代器也就是节点指针指向的内容不能修改。例如it是const类型迭代器的对象,*it就可以,++it也可以,但是(*it)++就不可以。

5.构造函数

		void empty_Init(){_head = new node;_head->_next = _head;_head->_prev = _head;}list(){empty_Init();}template<class Iterator>list(Iterator first, Iterator end){empty_Init();//别忘加上哨兵位,没有哨兵位识别不了endwhile (first != end){push_back(*first);first++;//这里的++first会调用重载的,因为传过来的是一个迭代器}}

哨兵位是空的,不放数据,但是哨兵位是正向迭代器的end,要加上。

默认无参构造就只有哨兵位,提供的迭代器的构造也要有哨兵位。

first++不用担心,first是迭代器类型的,所以会调用迭代器的++。 

6.拷贝构造

		//传统的拷贝构造//list(const list<T>& lt)//{//	empty_Init();//	for (auto e : lt)//	{//		push_back(e);//this->push_back(e)//	}//}void swap(list<T>& tmp)//要使用库中的swap,而库中的swap就不带const;况且交换的是头节点,const修饰的就不能修改指向{std::swap(_head, tmp._head);}//现代的拷贝构造list(const list<T>& lt){empty_Init();list<T> tmp(lt.begin(), lt.end());//为什么还要多一个变量,因为下面swap的参数没有const,而拷贝构造要加constswap(tmp);//this->swap(tmp)}

拷贝构造,直接使用库中的swap,交换头节点也就是哨兵位的指向就行,因为链表后面的关系都通过头节点找到,所以也就相当于都交换了。

注意库中swap的参数:

 

7.赋值重载

		list<T>& operator=(list<T> lt)//参数不能使用引用,使用引用再使用swap交换,原来赋值的值就被改了{swap(lt);return *this;}

一样是使用库中的swap,但是赋值的参数不能是引用,例如L1=L3,用引用再加上使用swap交换头节点的指向,L3就被改了,我们要求的是赋值是不能改变赋过来的对象的,内置类型也是(a=b)。 

 

8.insert

		void insert(iterator pos,const T& x){node* cur = pos._node;node* prev = cur->_prev;node* newnode = new node(x);prev->_next = newnode;newnode->_prev = prev;newnode->_next = cur;cur->_prev = newnode;}

链接节点即可,注意插入的值可能是任意类型,所以要用模版参数并且带上const与引用,防止是内置类型的值是const,传过来权限放大。

插入pos位置,也就是在pos前和pos位置之间插入。 

 

9.erase

		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 pos._node;return iterator(next);}

注意删除完返回删除数据的下一个迭代器位置。

删除就是找前找后,删除节点,链接前后。

_node是new出来的,注意配套使用。

 

10.析构

void clear()
{iterator it = begin();while (it != end()){it= erase(it);//删除后返回的是下一个数据的位置,所以循环就走起来了}
}~list()
{clear();delete _head;_head = nullptr;
}

注意迭代器的erase删除后返回的是删除数据的下一个迭代器位置,所以用it接收就不怕迭代器失效了,同时循环也走起来了。 

11.头插头删,尾插尾删

		void push_back(const T& x){/*node* tail = _head->_prev;node* newnode = new node(x);tail->_next = newnode;newnode->_prev = tail;_head->_prev = newnode;newnode->_next = _head;*/insert(end(), x);}void push_front(const T& x){insert(begin(),x);}void pop_back(){erase(--end());}void pop_front(){erase(begin());}

直接复用即可。 

12.完整代码+简单测试

封装的反向迭代器: 

#pragma oncenamespace my_iterator
{template<class Iterator,class Ref,class Ptr>struct ReverseIterator{typedef ReverseIterator<Iterator,Ref,Ptr> self;Iterator _cur;ReverseIterator(Iterator it):_cur(it){}Ref operator*(){Iterator tmp = _cur;//因为要--,而解引用是不能改值的,所以用tmp改并返回--tmp;return *tmp;}Ptr operator->(){return &operator*();}self operator++(){--_cur;//直接的++--就能直接改了,所以可以直接返回原对象return *this;}self operator--(){++_cur;return *this;}bool operator!=(const self& s){return _cur != s._cur;}};
}
#pragma once
#include "my_iterator.h"#include <iostream>
#include <assert.h>
#include <list>using namespace my_iterator;
using namespace std;namespace my_list
{template<class T>struct list_node{list_node<T>* _prev;list_node<T>* _next;T _data;list_node(const T& x= T())//这里不给缺省值可能会因为没有默认构造函数而编不过:_prev(nullptr),_next(nullptr),_data(x){}};template<class T,class Ref,class Ptr>struct _list_iterator{typedef list_node<T> node;typedef _list_iterator<T, Ref, Ptr> self;node* _node;//对迭代器也就是节点的指针进行封装,因为list迭代器是不能直接++的_list_iterator(node* n):_node(n){}Ref operator*()//返回的必须是引用,不然改变不了外面的对象的成员,要支持对自己解引用改变值就要用应用{return _node->_data;}Ptr operator->(){return &(_node->_data);//返回地址,再解引用直接访问数据}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& s){return _node != s._node;}bool operator==(const self& s){return _node == s._node;}};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;typedef ReverseIterator<iterator,T&,T*> reverse_iterator;typedef ReverseIterator<iterator, const T&, const T*> const_reverse_iterator;void empty_Init(){_head = new node;_head->_next = _head;_head->_prev = _head;}list(){empty_Init();}template<class Iterator>list(Iterator first, Iterator end){empty_Init();//别忘加上哨兵位,没有哨兵位识别不了endwhile (first != end){push_back(*first);first++;//这里的++first会调用重载的,因为传过来的是一个迭代器}}//传统的拷贝构造//list(const list<T>& lt)//{//	empty_Init();//	for (auto e : lt)//	{//		push_back(e);//this->push_back//	}//}void swap(list<T>& tmp)//要使用库中的swap,而库中的swap就不带const;况且交换的是头节点,const修饰的就不能修改指向{std::swap(_head, tmp._head);}//现代的拷贝构造list(const list<T>& lt){empty_Init();list<T> tmp(lt.begin(), lt.end());//为什么还要多一个变量,因为下面swap的参数没有const,而拷贝构造要加constswap(tmp);//this->swap(tmp)}list<T>& operator=(list<T> lt)//参数不能使用引用,使用引用再使用swap交换,原来赋值的值就被改了{swap(lt);return *this;}void clear(){iterator it = begin();while (it != end()){it= erase(it);//删除后返回的是下一个数据的位置,所以循环就走起来了}}~list(){clear();delete _head;_head = nullptr;}iterator begin(){return iterator(_head->_next);}iterator end(){return iterator(_head);//哨兵位就是end}const_iterator begin() const//本身const迭代器是让迭代器指向的内容不能修改,但是这样用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());}void push_back(const T& x){/*node* tail = _head->_prev;node* newnode = new node(x);tail->_next = newnode;newnode->_prev = tail;_head->_prev = newnode;newnode->_next = _head;*/insert(end(), x);}void push_front(const T& x){insert(begin(),x);}void pop_back(){erase(--end());}void pop_front(){erase(begin());}void insert(iterator pos,const T& x){node* cur = pos._node;node* prev = cur->_prev;node* newnode = new node(x);prev->_next = newnode;newnode->_prev = prev;newnode->_next = cur;cur->_prev = newnode;}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 pos._node;return iterator(next);}private:node* _head;};void print_list(const list<int>& lt){list<int>::const_iterator it = lt.begin();//不能直接这样写,传递过来的this指针也是const list<int>*,权限放大了,要提供const版本while (it != lt.end()){cout << *it << " ";++it;}cout << endl;}void test_list1(){list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);list<int>::iterator it = lt.begin();//=调用默认的拷贝构造,是浅拷贝,但是可以,让it也指向begin的位置while (it != lt.end()){cout << *it << " ";++it;}cout << endl;for (auto e : lt){cout << e << " ";}cout << endl;print_list(lt);}struct AA{int _a1;int _a2;AA(int a1 = 0, int a2 = 0):_a1(a1), _a2(a2){}};void test_list2(){list<AA> lt;lt.push_back(AA(1, 1));lt.push_back(AA(2, 2));lt.push_back(AA(3, 3));list<AA>::iterator it = lt.begin();while (it != lt.end()){//cout << (*it)._a1 << " "<<(*it)._a2<<endl;cout << it->_a1 << " " << it->_a2 << endl;//面对这样的类型,需要重载->,.也可以访问,但是有点别扭++it;}cout << endl;}void test_list3(){list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);auto pos = lt.begin();++pos;lt.insert(pos, 20);for (auto e : lt){cout << e << " ";}cout << endl;lt.push_back(100);lt.push_front(1000);for (auto e : lt){cout << e << " ";}cout << endl;lt.pop_back();lt.pop_front();for (auto e : lt){cout << e << " ";}cout << endl;}void test_list4(){list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);for (auto e : lt){cout << e << " ";}cout << endl;lt.clear();for (auto e : lt){cout << e << " ";}cout << endl;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(40);for (auto e : lt){cout << e << " ";}cout << endl;}void test_list5(){list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);for (auto e : lt){cout << e << " ";}cout << endl;list<int> lt2(lt);for (auto e : lt2){cout << e << " ";}cout << endl;list<int> lt3;lt3.push_back(10);lt3.push_back(20);lt3.push_back(30);for (auto e : lt3){cout << e << " ";}cout << endl;lt2 = lt3;for (auto e : lt2){cout << e << " ";}cout << endl;}void test_list6(){list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);list<int>::iterator it = lt.begin();//=调用默认的拷贝构造,是浅拷贝,但是可以,让it也指向begin的位置while (it != lt.end()){(*it) *= 2;cout << *it << " ";++it;}cout << endl;list<int>::reverse_iterator rit = lt.rbegin();while (rit != lt.rend()){cout << *rit << " ";++rit;}cout << endl;/*for (auto e : lt){cout << e << " ";}cout << endl;print_list(lt);*/}}

总结:

重点在迭代器与反向迭代器的的封装,其它的内容与其它的容器大致相同。

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

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

相关文章

机器学习周报第37周

目录 一、文献阅读&#xff1a;You Only Look Once: Unified, Real-Time Object Detection1.1 摘要1.2 背景1.3 论文模型1.4 网络设计1.5 YOLO的局限性1.6 实现代码 一、文献阅读&#xff1a;You Only Look Once: Unified, Real-Time Object Detection 1.1 摘要 YOLO是一种新…

比起本地渲染,网渲的优势在哪里?渲染100邀请码1a12

网渲的应用很广泛&#xff0c;在建筑设计和室内装修等行业都能看到它的身影&#xff0c;比起本地渲染&#xff0c;它有以下几个优势。 1、资源充足 网渲平台的资源充足&#xff0c;会根据渲染作业的规模和复杂度自动扩展或缩减分配&#xff0c;以达到动态调节的目的&#xff0c…

王道汽车4S企业管理系统 SQL注入漏洞复现

0x01 产品简介 王道汽车4S企业管理系统(以下简称“王道4S系统”)是一套专门为汽车销售和维修服务企业开发的管理软件。该系统是博士德软件公司集10余年汽车行业管理软件研发经验之大成,精心打造的最新一代汽车4S企业管理解决方案。 0x02 漏洞概述 王道汽车4S企业管理系统…

软件项目总体测试计划(Word原件2024)

一、 前言 &#xff08;一&#xff09; 背景 &#xff08;二&#xff09; 目的 &#xff08;三&#xff09; 测试目标 &#xff08;四&#xff09; 适用范围与读者对象 &#xff08;五&#xff09; 术语与缩写 二、 软件测试实施流程 &#xff08;一&#xff09; 测试工作总体流…

【RSGIS数据资源】2001-2022年中国玉米种植分布数据集

文章目录 数据介绍精彩截图2001&#xff5e;2020年中国玉米种植频率分布2001年至2020年研究区域融合数据的平均填充百分比。 数据介绍 2001-2022年中国玉米种植分布数据集&#xff08;CCD-Maize&#xff09;&#xff0c;涵盖中国22个省、市的玉米种植分布图&#xff0c;文件格…

授权协议OAuth 2.0之如何接入授权服务

写在前面 为了能够更好以场景化的方式来理解OAuth2.0&#xff0c;本文一起看下&#xff0c;假定我们现在要开发一个交友类软件&#xff0c;为了提高用户登录的便利程度&#xff0c;需要对接微信开放平台&#xff0c;获取到用户的微信账号信息&#xff0c;作为用户的注册信息来…

使用SpringBoot将中国地震台网数据保存PostGIS数据库实践

目录 前言 一、数据转换 1、Json转JavaBean 2、JavaBean与数据库字段映射 二、空间数据表设计 1、表结构设计 三、PostGIS数据保存 1、Mapper接口定义 2、Service逻辑层实现 3、数据入库 4、运行实例及结果 总结 前言 在上一篇博客中基于Java的XxlCrawler网络信息爬…

判断二叉树是否对称

解题思路&#xff1a;首先判断特殊情况&#xff0c;比如左右子树是否为一空一有&#xff0c;是否为两空&#xff0c;是否相等&#xff0c;然后递归判断外侧是否相等&#xff08;即为左子树的左节点和右子树的右节点&#xff09;和内侧是否相等&#xff08;即为右子树的左节点和…

LeetCode 289.生命游戏————2024 春招冲刺百题计划

根据 百度百科 &#xff0c; 生命游戏 &#xff0c;简称为 生命 &#xff0c;是英国数学家约翰何顿康威在 1970 年发明的细胞自动机。 给定一个包含 m n 个格子的面板&#xff0c;每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态&#xff1a; 1 即为 活细胞 &am…

【LeetCode热题100】【回溯】单词搜索

题目链接&#xff1a;79. 单词搜索 - 力扣&#xff08;LeetCode&#xff09; 要在一个二维数组里面找到一条单词路径&#xff0c;可以先遍历二维数组找到单词入口&#xff0c;然后往上下左右深度遍历&#xff0c;访问过的元素直接修改成字符串结束符&#xff0c;访问完改回去 …

荣誉 | 人大金仓获评轨交行业“智慧运维优秀应用案例”

4月12日至13日&#xff0c;2024&#xff08;第八届&#xff09;中国城市轨道交通智慧运维大会在成都顺利举行。会上&#xff0c;人大金仓以其在轨交行业的卓越贡献和创新实践&#xff0c;获评“智慧运维优秀应用案例”。公司副总裁梁红凤出席大会并发表了题为“打造世界一流的数…

XXL-JOB v2.4.1 版本正式发布!

v2.4.1 Release Notes 1、【优化】多个项目依赖升级至较新稳定版本&#xff0c;涉及 netty、groovy、springboot、mybatis 等&#xff1b;2、【修复】“CVE-2022-43402” groovy 低版本漏洞修复。3、【修复】“CVE-2024-29025” netty 低版本漏洞修复。4、【修复】“CVE-2024-…