《C++ list的模拟实现》

news/2024/10/17 22:17:28/

本文主要介绍list容器的模拟实现

文章目录

  • 1、迭代器
    • 正向迭代器类
    • 反向迭代器类
  • 2、push_back尾插函数
  • 3、 push_front头插函数
  • 4、 insert插入函数
  • 5、erase删除函数
  • 6、pop_front函数
  • 7、pop_back函数
  • 8、 构造函数
  • 9、 拷贝构造函数
  • 10、 list赋值重载函数
  • 11、clear
  • 12、 析构函数
  • 程序源码
    • list.h
    • Reverse_Iterator.h


list示意图:
在这里插入图片描述
首先需要定义一个节点 的结构体

//节点template <class T>struct list_node{list_node<T>* _next;list_node<T>* _prev;T _data;//构造函数list_node(const T& x = T()):_next(nullptr), _prev(nullptr), _data(x){}};

1、迭代器

正向迭代器类

我们之前所理解的是:迭代器理解为像指针一样的东西,但是在list中有些不同

// 迭代器逻辑
while(it!=l.end())
{*it; // 解引用取数据++it;// 自加到达下一个位置
}

我们可以来观察一下STL源码中大佬是怎么封装的:
在这里插入图片描述
我们可以看到,只有一个成员,那就是一个结点的指针node,link_type又是一个自定义类型的指针,我们原生类型的指针在vector或者string中是可以直接typedef成为迭代器的,但是list底层是双链表,数据结构并非连续的,所以直接*it或者++it是不能够完成迭代器的任务的,但是C++中支持对于自定义类型的运算符重载,我们可以对解引用和自加两个运算符重载。

++it:就是当前指针存放下一个结点的地址
*it:解引用当前节点,取出值来

迭代器中,拷贝构造、运算符赋值重载、析构都不需要自己实现,使用默认生成的即可(即浅拷贝),因为迭代器是用自定义类型的指针封装的,访问修改链表,节点属于链表,不属于迭代器,所以不用管它。

我们在传入const版本的list时,list是const对象,需要的是const_iterator,这里会出现错误,不能将const的list的迭代器传给普通迭代器。如下所示例子:

void print_list(const list<int>& lt)
{// lt.begin()是const迭代器(只可读)// it是普通迭代器(可读可写)list<int>::iterator it = lt.begin();while (it != lt.end()){cout << *it << " ";++it;}
}

现在我们如何实现一个const的迭代器呢?
意思就是只可以读不能够写。可以++,- -,*解引用,但是解引用时不能修改数据。
可以想到这种写法:

const T& operator*()const
{return _node->_data;
}T& operator*()
{return _node->_data;
}

但是并不是迭代器是const的,而是我们传入的list容器是const版本的。

我们可以将写一个const_iterator 的类版本,这样普通迭代器和const迭代器就不是一个类型了,是两个不同的类型了,这样会造成代码冗余。

template<class T>
struct __const_list_iterator
{//...// __list_iterator全部替换为__const_list_iterator
};

优化:
增加一个模板参数class Ref
在这里插入图片描述
这样第一个模板参数都是T,我们可以根据传入的第二个参数来推出时T&还是const T&,本来我们是要实现两个类的,现在只需要增加一个模板参数即可,这里体现出了C++泛型的优势!
迭代器我们说,它是像指针一样的东西,如果它是指向的一个结构体,需要用它的成员变量,我们还需要重载->箭头

struct Date {int _year;int _month;int _day;Date(int year = 0, int month = 0, int day = 0)//这里要给默认参数,因为需要构建一个哨兵位头结点:_year(year), _month(month), _day(day){}
};
void test_list2()
{list<Date> lt;lt.push_back(Date(2022, 1, 1));lt.push_back(Date(2022, 1, 2));lt.push_back(Date(2022, 1, 3));lt.push_back(Date(2022, 1, 4));// 现在来遍历日期类list<Date>::iterator it = lt.begin();while (it != lt.end()){cout << (*it)._year << "/" << (*it)._month << "/" << (*it)._day << endl;++it;}cout << endl;
}

这里的*解引用然后再去.,我们可以重载->,让他可以去调用结构体的成员,这样更加快捷高效方便。

T* operator->()
{return &(_node->_data);
}

在这里插入图片描述
进一步解释:
*it调用operator*,返回一个结点对象,对象再.操作,拿到数据
it->调用operator->,返回对象的指针,(这里返回的是原生指针)再通过->调用用结构体成员,这里实际上应该是it->->_year,但是这样写,可读性很差,所以编译器做了一个优化,省略了一个->,所以所有的类型只要想要重载->,都会这样优化省略一个->

这里又会衍生出一个问题,那就是如果使用const_iterator,使用->也会修改数据,所以再增加一个模板参数
在这里插入图片描述

// 正向迭代器类
template<class T, class Ref, class Ptr>
struct __list_iterator
{typedef	ListNode<T> Node;typedef __list_iterator<T, Ref, Ptr> self;// 再次typedef,方便后续的修改Node* _node;__list_iterator(Node* x)// 迭代器的实质,就是自定义类型的指针:_node(x){}// ++it 返回++之后的引用对象self& operator++(){_node = _node->_next;return *this;}// it++ 返回++之前的对象self operator++(int){self  tmp(this);_node = _node->_next;return tmp;}// --it self& operator--(){_node = _node->_prev;return *this;}// it-- self operator--(int){self tmp(this);_node = _node->_prev;return tmp;}// 返回引用,可读可写Ref operator*(){return _node->_data;}// 返回对象的指针Ptr operator->(){return &(_node->_data);}bool operator!=(const self& it)const{return _node != it._node;}bool operator==(const self& it)const{return _node == it._node;}
};

反向迭代器类

实质:对于正向迭代器的一种封装
反向迭代器跟正想迭代器区别就是++,- -的方向是相反的
所以反向迭代器封装正向迭代器即可,重载控制++,- -的方向
在这里插入图片描述

#pragma once
// reverse_iterator.h
namespace sjj 
{template <class Iterator, class Ref, class Ptr>class reverse_iterator{typedef reverse_iterator<Iterator,Ref,Ptr> self;public:reverse_iterator(Iterator it):_it(it){}// 比较巧妙,解引用取的是当前位置的前一个位置的数据// operator*取前一个位置, 主要就是为了让反向迭代器开始和结束跟正向迭代器对称Ref operator *(){Iterator tmp = _it;return *--tmp;}Ptr operator->(){return &(operator*());}self& operator++(){--_it;return *this;}self operator++(int){self tmp = *this;--_it;return tmp;}self& operator--(){++_it;return *this;}self operator--(int){self tmp = *this;++_it;return tmp;}bool operator!=(const self& rit){return _it != rit._it;}bool operator==(const self& rit){return _it == rit._it;}private:Iterator _it;};
}

2、push_back尾插函数

在这里插入图片描述

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;tail = tail->_next;*/// 复用insert函数insert(end(), x);
}

3、 push_front头插函数

// 头插
void push_front(const T& x)
{// 复用insert函数insert(begin(), x);
}

4、 insert插入函数

在这里插入图片描述


// 在pos位置前插入
iterator 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;return iterator(newnode);// 返回新插入结点位置的迭代器
}

注意:这里list的insert函数,pos位置的迭代器不会失效,因为pos指向的位置不会改变,vector中迭代器失效的原因是因为挪动数据,导致指向的位置的数据发生变化。

5、erase删除函数

在这里插入图片描述

iterator erase(iterator pos)
{assert(pos != end());//不能将哨兵位的头结点给删除了Node* prev = pos._node->_prev;Node* next = pos._node->_next;delete pos._node;prev->_next = next;next->_prev = prev;return iterator(next);// 返回pos位置的下一个位置的迭代器
}

注意:这里的pos位置的迭代器一定会失效,因为都已经将结点给删除了。

6、pop_front函数

// 复用erase函数
void pop_front()
{erase(begin());
}

7、pop_back函数

// 复用erase函数
void pop_back()
{erase(--end());
}

8、 构造函数

//空构造,复用后就不用写初始化列表了
void emptyInit()
{_head = new Node;_head->_next = _head;_head->_prev = _head;
}list()
{emptyInit();
}// 函数模板,用迭代器区间进行初始化
template<class InputIterator>
list(InputIterator first, InputIterator last)
{emptyInit();while (first != last){push_back(*first);++first;}
}list(size_t n, const T& val = T())
{emptyInit();for (size_t i = 0; i < n; ++i){push_back(val);}
}

注意:
在这里插入图片描述
这两个构造函数一起使用可能会存在问题,填充版本和构造器版本可能会存在冲突,如下例子:

struct Date {int _year;int _month;int _day;Date(int year = 0, int month = 0, int day = 0)//这里要给默认参数,因为有一个哨兵位头结点需要初始化:_year(year), _month(month), _day(day){}
};
void test_list4()
{list<Date> lt1(5, Date(2022, 9, 9));for (auto e : lt1){cout << e._year << "/" << e._month << "/" << e._day << endl;}cout << endl;list<int> lt2(5, 1);for (auto e : lt2){cout << e << " ";}cout << endl;
}

对于这两个:在实例化时会调用更加匹配的构造函数初始化
list lt1(5, Date(2022, 9, 9))它会正常调用list(size_t n, const T& val = T())

list lt2(5, 1)而它会将5和1推演成两个int,进而去匹配这个迭代器版本的构造函数
template < class InputIterator> list(InputIterator first, InputIterator last),但是与我们的本意,用n个val初始化原意相背,而其中有个*first,这里int去解引用必会报错

改进:再多提供第一个参数是int重载版本的list(int n, const T& val = T())构造函数

list(int n, const T& val = T())
{emptyInit();for (size_t i = 0; i < n; ++i){push_back(val);}
}

9、 拷贝构造函数

浅拷贝会崩溃的原因是,同一块空间被析构了两次,所以我们要完成深拷贝

// lt2(lt1)
list(const list<T>& lt)
{emptyInit();list<T> tmp(lt.begin(), lt.end());std::swap(_head, tmp._head);
}

10、 list赋值重载函数

// 现代写法
list<T>& operator=(list<T> lt)
{std::swap(_head, lt._head);return *this;
}

11、clear

// 清空
void clear()
{iterator it = begin();while (it != end()){erase(it++); // 也可以复用erase,it++返回加加之前的值}
}

12、 析构函数

~list()
{clear();// 析构与clear不同,要将哨兵位头结点给删除了delete _head;_head = nullptr;
}

程序源码

list.h

#pragma once
#include <assert.h>
#include "Reverse_Iterator.h"
namespace mwq
{template <class T>struct list_node{struct list_node* _next;struct list_node* _prev;T _data;list_node(const T& x = T()){_next = nullptr;_prev = 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_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 temp(*this);_node = _node->_next;return temp;}Self& operator--(){_node = _node->_prev;return *this;}Self operator--(int){Self temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& s){return _node != s._node;}bool operator==(const Self& s){return _node == s._node;}};template <class T>class list{public:typedef  list_node<T> node;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 Swap(list<T>& temp){std::swap(_head, temp._head);}void emptyInit(){_head = new node;_head->_next = _head;_head->_prev = _head;}list(){emptyInit();}template <class InputIterator>list(InputIterator first, InputIterator last){emptyInit();while (first != last){push_back(*first);++first;}}list(const list<T>& lt){emptyInit();list<T> temp(lt.begin(), lt.end());Swap(temp);}list<T>& operator=(list<T> temp){emptyInit();Swap(temp);return *this;}iterator begin(){return iterator(_head->_next);}iterator end(){return iterator(_head);}//反向迭代器reverse_iterator rbegin(){return reverse_iterator(end());}reverse_iterator rend(){return reverse_iterator(begin());}const_iterator begin()const {return const_iterator(_head->_next);}const_iterator end()const{return const_iterator(_head);}void push_back(const T& x){/*node* tail = _head->_prev;node* newnode = new node(x);tail->_next = newnode;newnode->_prev = tail;newnode->_next = _head;_head->_prev = newnode;*/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(!empty());node* cur = pos._node;node* prev = cur->_prev;node* next = cur->_next;prev->_next = next;next->_prev = prev;return iterator(next);}bool empty()const {return _head->_next == _head;}void clear(){auto it = begin();while (it != end()){it = erase(it);			}}~list(){clear();delete _head;_head = nullptr;}private:node* _head;};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();while (it != lt.end()){cout << *it << " ";++it;}cout << endl;list<int> lt2;lt2 = lt;list<int>::iterator it2 = lt2.begin();while (it2 != lt2.end()){cout << *it2 << " ";++it2;}cout << endl;list<int>::reverse_iterator rit = lt.rbegin();while (rit != lt.rend()){cout << *rit << " ";++rit;}cout << endl;}
}

Reverse_Iterator.h

#pragma once
namespace mwq
{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 temp(_cur);--temp;return *temp;}Ptr operator->(){Iterator temp(_cur);--temp;return temp;}Self& operator++(){--_cur;return *this;}Self operator++(int){Self temp(*this);--_cur;return temp;}Self& operator--(){++_cur;return *this;}Self operator--(int){Self temp(*this);++_cur;return temp;}bool operator!=(const Self& s){return _cur != s._cur;}bool operator==(const Self& s){return _cur == s._cur;}};
}

http://www.ppmy.cn/news/149467.html

相关文章

Yolov8轻量级:VanillaNet一种新视觉Backbone,极简且强大!华为诺亚2023

简到极致、浅到极致!深度为6的网络即可取得76.36%@ImageNet的精度,深度为13的VanillaNet甚至取得了83.1%的惊人性能。 1.VanillaNet 论文:https://arxiv.org/pdf/2305.12972.pdf 来自华为诺亚、悉尼大学的研究者们提出了一种极简的神经网络模型 VanillaNet,以极简主义的设…

git合并代码后,目录被删除了

问题&#xff1a; 同事x在a分支使用git checkout b -- test.md命令抽取b的文件&#xff0c;然后把代码合并到merge-c。 同事y在merge-c分支&#xff0c;合并了自己的分支b&#xff0c;然后拉取同事x的分支&#xff0c;发现产生了冲突&#xff0c;解决了冲突后提交。 最后发现自…

LNMP及论坛搭建

文章目录 LNMP及论坛搭建1 Nginx1.1 关闭防火墙1.2 安装依赖包1.3 创建运行用户、组1.4 编译安装nginx1.5 优化路径1.6 添加nginx系统服务 2 MySQL服务2.1 安装Mysql环境依赖包2.2 创建运行用户2.3 编译安装2.4 修改mysql配置文件2.5 更改mysql安装目录和配置文件的属主属组2.6…

vivo iQOOX80 X70 X60 X30 S9 S6 Y53sY52s Y31s U5x Z1x手撕账户

vivo iQOOX80 X70 X60 X30 S9 S6 Y53sY52s Y31s U5x Z1x手撕账户 OPPO vivo iQOO手撕 iCloud云空间 133287550

(C语言)数组去重

现有一组数&#xff0c;a[]{1,1,1,3,3,5,5,5,5,6,6,8,8,9,10,10} 要求将他们变为&#xff1a;{1&#xff0c;3&#xff0c;5&#xff0c;6&#xff0c;8&#xff0c;9&#xff0c;10} #include<stdio.h> int fun(int a[],int n){&#xff0c;int i,j1,ka[0],m,flag0;for…

c语言中%s的用法

转自&#xff1a;https://www.pinlue.com/article/2020/03/3100/5310073904413.html C语言是计算机软件领域非常经典的编程语言,unix、linux等众多操作系统均是由C语言编写而成。而在硬件控制、底层驱动等应用领域,C语言更是具有不可替代的作用。下面小编就跟你们详细介绍下c语…

三星s6 html5测试分数,vivos6跑分成绩多少性能怎么样 vivos6手机安兔兔跑分及性能实测分析...

vivos6跑分成绩多少&#xff1f;vivos6性能怎么样?对于最新发布的高颜值vivos6手机&#xff0c;很多的女生用户可是非常的喜欢&#xff0c;而且性价比也非常的高&#xff0c;但是vivos6手机的性能到底怎么样&#xff1f;vivos6手机跑分成绩有多少呢&#xff1f;下面就和小编一…

C语言%*s用法

1.在scanf中使用,则添加了*的部分会被忽略(跳过),不会被参数获取。 例如&#xff1a; [cpp] view plain copy int a,b; char b[10]; scanf("%d%*s",&a,b); 输入为&#xff1a; 12 abc 那么12将会读取到变量a中&#xff0c;但是后面的abc将在读取之后抛…