C++ list模拟实现

这篇具有很好参考价值的文章主要介绍了C++ list模拟实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

list模拟实现代码:

namespace djx
{
	template<class T>
	struct list_node
	{
		T _data;
		list_node<T>* _prev;
		list_node<T>* _next;

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

	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* node)
			:_node(node)
		{}

		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;
		
		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

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

		const_iterator end()const
		{
			return _head;
		}

		void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			_size = 0;
		}

		list()
		{
			empty_init();
		}

		list(const list<T>& lt)
		{
			empty_init();
			for (auto e : lt)
			{
				push_back(e);
			}
		}

		void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
			std::swap(_size, lt._size);
		}

		list<T>& operator=(list<T> lt)
		{
			swap(lt);
			return *this;
		}

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

		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}

		void push_back(const T& x)
		{
			insert(end(), x);
		}

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

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

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

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

			prev->_next = newnode;
			newnode->_prev = prev;

			newnode->_next = cur;
			cur->_prev = newnode;
			_size++;
			return newnode;
		}

		iterator erase(iterator pos)
		{
			Node* cur = pos._node;
			Node* next = cur->_next;
			Node* prev = cur->_prev;

			delete cur;
			prev->_next = next;
			next->_prev = prev;
			_size--;
			return next;
		}
		
		size_t size()
		{
			return _size;
		}

	private:
		Node* _head;
		size_t _size;
	};
}

源码中的list实现为带头双向链表

C++ list模拟实现,C++,c++,list

 文章来源地址https://www.toymoban.com/news/detail-679593.html

list类的对象有两个成员:指向头结点的指针_head,统计数据个数的_size

在模拟实现list之前,需要先模拟实现结点类,迭代器类

结点类:三个成员,_data _prev _next实现成struct(也是类,不过与class不同的是,它的成员都是公开的,都可以在类外访问),因为这三个成员,在迭代器类中都要使用访问,设it是迭代器,*it就会返回结点中值(_data)的引用,it++(要访问结点中的_next) , it--(要访问结点中的_prev)

    template<class T>
	struct list_node
	{
		T _data;
		list_node<T>* _prev;
		list_node<T>* _next;

		list_node(const T& x = T())//x是匿名对象的引用,const延长了匿名对象的生命周期,x销毁,匿名对象才销毁,匿名对象会调用它的构造函数,完成初始化
			:_data(x)
			,_prev(nullptr)
			,_next(nullptr)
		{}
	};

要写构造函数:list类中的push_back插入数据时,需要new一个结点,并传数值

                         调用构造函数时,若是直接使用编译器生成的默认构造函数,则无法传参

构造函数的参数设计成缺省参数:有传实参过来就使用此值,没有传参过来就用匿名对象去拷贝构造_data,使用匿名对象去拷贝构造_data的情形:list类中的无参构造函数-->让list中的成员变量_head指向一个new出来的头结点,头结点中不存储任何有效数据,故而new时无需传参

迭代器类:一个成员 _node(结点的指针)

设计成struct:在list类中设计insert和erase时,传参给它们的是iterator迭代器,我们要使用迭代器中的成员变量(结点的指针)即要访问迭代器中的成员,那么设计成struct会比设计成class类方便不少

list的迭代器与vector,string类不同,在模拟实现vector和string的迭代器时,它们可以用原生指针来实现,因为完美契合原生指针的行为,但是模拟实现list的迭代器时,它必须设计成一个类,是对原生指针的封装,原因:

若是list的迭代器就用原生指针来实现,那么*it(it是一个迭代器)得到的不是数据,而是结点

it++ 不能走向下一个数据,故而需要对原生指针进行封装,让*it得到数据,it++,走向下一个数据

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* node)//要写带参的构造,因为在list类中实现begin()时,返回值的类型是迭代器,但是我们返回的可以是结点的指针,单参数的构造函数支持隐式类型转换,也可以是迭代器,但是此迭代器中的成员变量(结点的指针)需要和第一个结点的指针一样
			:_node(node)
		{}

		Ref operator*()//Ref可以是T&(普通迭代器) const T& (const迭代器)
		{
			return _node->_data;
		}

		Ptr operator->()Ptr可以是T* (普通迭代器) const T* (const迭代器)
		{
			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;
		}
	};

迭代器有非const对象调用的,也有const对象调用的,二者的区别仅仅是能否修改的问题,*迭代器返回的是数据的引用,const对象调用的迭代器返回的也是数据的引用,但是const修饰的

迭代器-> 返回的是数据的地址,const对象调用的迭代器返回的是const修饰的数据地址

(迭代器可以看作是模拟原生指针的行为,若是数据为自定义类型,那么迭代器->就可以访问到自定义类型对象中的成员,实际上看成是原生指针的迭代器-> 无法做到,但是对原生指针封装而出现的迭代器可以做到,只要迭代器->返回的是数据的指针,那么有了自定义类型对象指针,不就可以访问它里面的成员了吗)

综上来看,我们只需要写一份迭代器类的模板,根据实例化参数的不同,生成不同的迭代器

迭代器需要三个模板参数:T(迭代器类中的成员变量是结点的指针,结点实例化需要)

模板参数 Ref  : 迭代器类中重载*运算符所用,重载*运算符的函数要返回数据的引用,而若是const对象的迭代器解引用,就要用const去修饰返回值

模板参数Ptr :迭代器类中重载->运算符所用,重载->运算符的函数返回数据的指针,而若是const对象的迭代器->,也要用const去修饰返回值

那么在list类中,设计普通迭代器,const对象调用的迭代器时,就可以用迭代器类的模板,实例化参数不同就会是完全不同的类型,普通迭代器用迭代器类的模板实例化,传参 T   T&   T*

const对象调用的迭代器用迭代器类的模板实例化,传参 T  const T&   const T*

构造函数:

1 无参的构造

    让list对象中的成员变量_head指向一个头指针(双向循环)

    参照源码list的实现:

C++ list模拟实现,C++,c++,list

 

        void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			_size = 0;
		}

		list()
		{
			empty_init();
		}

2 拷贝构造(深拷贝)

        list(const list<T>& lt)
		{
			empty_init();
			for (auto e : lt)
			{
				push_back(e);
			}
		}

析构函数:

        ~list()
		{
			clear();
			delete _head;//释放头结点
			_head = nullptr;
		}

		void clear()//清除数据
		{
			iterator it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}

赋值重载:

        void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
			std::swap(_size, lt._size);
		}

		list<T>& operator=(list<T> lt)///lt是实参的深拷贝,lt销毁会释放掉原本由*this申请的空间
		{
			swap(lt);//交换*this和lt
			return *this;
		}

迭代器:

        typedef __list_iterator<T, T&, T*> iterator;
		typedef __list_iterator<T, const T&, const T*> const_iterator;
		
		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

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

		const_iterator end()const
		{
			return _head;
		}

测试1:

void test1()
{
	djx::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);
	lt.push_back(5);

	djx::list<int>:: iterator it = lt.begin();
	while (it != lt.end())
	{
		*it += 20;
		cout << *it << " ";
		it++;
	}
	cout << endl;

	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
}

C++ list模拟实现,C++,c++,list

测试2:

void test2()
{
	djx::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);
	lt.push_back(5);

	djx::list<int> lt1(lt);//拷贝构造

	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;

	for (auto e : lt1)
	{
		cout << e << " ";
	}
	cout << endl;

	djx::list<int> lt2;
	lt2.push_back(100);
	lt2.push_back(200);
	lt2.push_back(300);
	lt2.push_back(400);
	lt2.push_back(500);

	lt1 = lt2;//赋值重载

	for (auto e : lt1)
	{
		cout << e << " ";
	}
	cout << endl;

	for (auto e : lt2)
	{
		cout << e << " ";
	}
	cout << endl;

}

C++ list模拟实现,C++,c++,list 

 

插入:

 1 push_back

        void push_back(const T& x)
		{
			insert(end(), x);
		}

2 push_front

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

3 insert

        iterator insert(iterator pos, const T& x)
		{
			Node* cur = pos._node;//当前节点的指针
			Node* newnode = new Node(x);
			Node* prev = cur->_prev;

			prev->_next = newnode;
			newnode->_prev = prev;

			newnode->_next = cur;
			cur->_prev = newnode;
			_size++;
			return newnode;//单参数的构造函数支持隐式类型转换
                           //或者写成:iterator(newnode)
		}

删除:

1 pop_back

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

2 pop_front

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

3 erase

        iterator erase(iterator pos)
		{
			Node* cur = pos._node;
			Node* next = cur->_next;
			Node* prev = cur->_prev;

			delete cur;
			prev->_next = next;
			next->_prev = prev;
			_size--;
			return next;//返回下一个数据的地址
		}

测试3:

struct AA
{
	AA(int a1 = 0, int a2 = 0)
		:_a1(a1)
		, _a2(a2)
	{}

	int _a1;
	int _a2;
};

void test3()
{
	djx::list<AA> lt;
	lt.push_back(AA(1, 1));
	lt.push_back(AA(2, 2));
	lt.push_back(AA(3, 3));

	djx::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;
}

C++ list模拟实现,C++,c++,list

题外:

 设计一个打印函数,打印任意list对象

template<typename T>//不可以用class
void print_list(const djx:: list<T>& lt)
{
    //list<T>未实例化的类模板,编译器不能去它里面去找
    //编译器就无法list<T>::const_iterator是内嵌类型,还是静态成员变量
    //前面加一个typename就是告诉编译器,这里是一个类型,等list<T>实例化,再去类里面找
	typename djx::list<T>::const_iterator it = lt.begin();
	while (it != lt.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;
}

打印任意容器

template<typename Container>
void print_container(const Container& con)
{
	typename Container::const_iterator it = con.begin();
	while (it != con.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;
}

测试4:

void test4()
{
	djx::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);
	print_list(lt);
}

C++ list模拟实现,C++,c++,list

测试5:

void test5()
{
	djx::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);
	print_container(lt);

	djx::list<string> lt1;
	lt1.push_back("1111111111111");
	lt1.push_back("1111111111111");
	lt1.push_back("1111111111111");
	lt1.push_back("1111111111111");
	lt1.push_back("1111111111111");
	//print_list(lt1);
	print_container(lt1);

	vector<string> v;
	v.push_back("222222222222222222222");
	v.push_back("222222222222222222222");
	v.push_back("222222222222222222222");
	v.push_back("222222222222222222222");
	print_container(v);

}

 C++ list模拟实现,C++,c++,list

 

到了这里,关于C++ list模拟实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 《C++ list的模拟实现》

    本文主要介绍list容器的模拟实现 list示意图: 首先需要定义一个节点 的结构体 我们之前所理解的是:迭代器理解为像指针一样的东西,但是在list中有些不同 我们可以来观察一下STL源码中大佬是怎么封装的: 我们可以看到,只有一个成员,那就是一个结点的指针node,link_

    2024年02月07日
    浏览(29)
  • 【C++】list的模拟实现

    list为任意位置插入删除的容器,底层为带头双向循环链表 begin() 代表第一个结点,end()代表最后一个结点的下一个 1. list_node 类设计 C++中,Listnode作为类名,而next和prev都是类指针,指针引用成员时使用-,而对象引用成员时使用 . 通过显示实例化,将两个类指针指定类型为T

    2024年02月02日
    浏览(34)
  • (C++) list底层模拟实现

     个人主页:Lei宝啊  愿所有美好如期而遇 首先,list底层是一个带头双向循环链表,再一个,我们还要解决一个问题,list的迭代器,vector和string的迭代器可以直接++,是因为他们的地址空间是连续的,而链表不是,所以链表的迭代器封装的不是原生指针,我们需要想办法解决

    2024年01月21日
    浏览(34)
  • 【C++学习手札】模拟实现list

    ​                                                        🎬 慕斯主页 : 修仙—别有洞天                                                        ♈️ 今日夜电波 : リナリア—まるりとりゅうが                                            

    2024年02月05日
    浏览(33)
  • C++——list类及其模拟实现

    前言:这篇文章我们继续进行C++容器类的分享—— list , 也就是数据结构中的链表 ,而且是 带头双向循环链表 。 由于要满足存储任意类型的数据,所以我们必须要使用模版来进行定义 。  关于list类中的最难之处,就是 迭代器 了。 因为 迭代器的原理即为指针 ,对于 st

    2024年04月10日
    浏览(31)
  • 【C++修炼之路】list 模拟实现

    👑作者主页:@安 度 因 🏠学习社区:StackFrame 📖专栏链接:C++修炼之路

    2024年02月16日
    浏览(28)
  • C++ list链表模拟实现

    目录 前言: 模拟实现: 迭代器的实现: list类功能函数实现:  初始化成空函数(empty_init): 构造函数:  拷贝构造函数: 尾插(push_back): 插入(insert): 删除(erase):  尾删(pop_back): 头插(push_front): 头删(pop_front):  清理(clear):  交换(swap): 赋值重载:

    2024年04月12日
    浏览(30)
  • C++:list使用以及模拟实现

    list是一个类模板,加类型实例化才是具体的类 。 list是可以 在任意位置进行插入和删除 的序列式容器。 list的 底层是双向循环链表结构 ,链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。 与其他序列式容器相比, list最大的

    2024年02月11日
    浏览(27)
  • C++ STL->list模拟实现

    list list文档 list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。 list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向 其前一个元素和后一个元素。 list与forward_list非常相似:最主

    2024年02月20日
    浏览(31)
  • 【C++】list容器功能模拟实现

            上一次介绍了list队容器的迭代器模拟,这次模拟实现list的简单功能,尤其要注意 构造函数、析构函数、以及赋值运算符重载 的实现。         list容器需要接纳所有类型的数据,因此,结构设置与迭代器设置同理,需要引入结点,数据。     //结点结构     templ

    2024年01月24日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包