C++中list的用法,模拟实现list

1. list用法

构造相关
list() 无参构造函数
list(size_type n, const value_type& val = value_type());构造一个list中包含n个value元素
list (const list& x) 拷贝构造
list (InputIterator first, InputIterator last) 用迭代器[first,last)区间的元素构造list

#include <iostream>
#include <list>
int main ()
{
	std::list<int> l1; // 构造空的l1
	std::list<int> l2 (4,100); // l2中放4个值为100的元素
	std::list<int> l3 (l2.begin(), l2.end()); // 用l2的[begin(), end())左闭右开的区间构造l3
	std::list<int> l4(l3); //用l3拷贝构造l4
	return 0;
}

迭代器相关
begin(),end() 返回第一个元素的迭代器,返回最后一个元素下一个位置的迭代器
rbegin(),rend() 返回第一个元素第一个元素的反向迭代器(即end()),返回最后一个元素下一个位置的反向迭代器(即begin())。

int main()
{
	int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	list<int> l(array, array + sizeof(array) / sizeof(array[0]));
	// 使用正向迭代器正向list中的元素
	for (list<int>::iterator it = l.begin(); it != l.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
	// 使用反向迭代器逆向打印list中的元素
	for (list<int>::reverse_iterator it = l.rbegin(); it != l.rend(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
	return 0;
}

容量相关
empty() 返回链表是否为空
size() 返回list中有效节点个数

插入删除
insert(iterator position, const value_type& val) 在position位置插入值为val的节点
push_back(const value_type& val) 尾插值为val的节点
push_front(const value_type& val) 头插值为val的节点
erase(iterator position) 删除position位置节点
pop_back() 删除尾部节点
pop_front() 删除头部节点
swap(list& x) 交换两个链表
clear() 将list中节点清空

#include <list>
void PrintList(list<int>& l)
{
	for (auto& e : l)
		cout << e << " ";
	cout << endl;
}


// push_back/pop_back/push_front/pop_front
void TestList1()
{
	int array[] = { 1, 2, 3 };
	list<int> L(array, array+sizeof(array)/sizeof(array[0]));
	// 在list的尾部插入4,头部插入0
	L.push_back(4);
	L.push_front(0);
	PrintList(L);
	// 删除list尾部节点和头部节点
	L.pop_back();
	L.pop_front();
	PrintList(L);
}


// insert /erase
void TestList3()
{
	int array1[] = { 1, 2, 3 };
	list<int> L(array1, array1+sizeof(array1)/sizeof(array1[0]));
	// 获取链表中第二个节点
	auto pos = ++L.begin();
	cout << *pos << endl;
	// 在pos前插入值为4的元素
	L.insert(pos, 4);
	PrintList(L);
	// 在pos前插入5个值为5的元素
	L.insert(pos, 5, 5);
	PrintList(L);
	// 在pos前插入[v.begin(), v.end)区间中的元素
	vector<int> v{ 7, 8, 9 };
	L.insert(pos, v.begin(), v.end());
	PrintList(L);

	// 删除pos位置上的元素
	L.erase(pos);
	PrintList(L);
	// 删除list中[begin, end)区间中的元素,即删除list中的所有元素
	L.erase(L.begin(), L.end());
	PrintList(L);
}
// resize/swap/clear
void TestList4()
{
	// 用数组来构造list
	int array1[] = { 1, 2, 3 };
	list<int> l1(array1, array1+sizeof(array1)/sizeof(array1[0]));
	PrintList(l1);
	// 交换l1和l2中的元素
	l1.swap(l2);
	PrintList(l1);
	PrintList(l2);
	// 将l2中的元素清空
	l2.clear();
	cout<<l2.size()<<endl;
}

2. 模拟实现list

#include <iostream>

namespace zhy
{
	template<class T>
	struct __list_node
	{
		__list_node<T>* _next;        //指向前驱节点
		__list_node<T>* _prev;        //指向后继节点
		T _date;                      //存放数据
		__list_node(const T& value=T())  //初始化节点
			:_date(value)
			, _next(nullptr)
			, _prev(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)
		{
		}
		//拷贝构造、赋值运算符重载、析构都用编译器默认生成的。因为迭代器的这些行为都是浅拷贝
		bool operator==(const self& x) const
		{
			return _node == x._node;
		}
		bool operator!=(const self& x) const
		{
			return _node != x._node;
		}
		self& operator++()
		{
			_node = _node->_next;
			return *this;
		}
		self operator++(int)           //不能返回引用,因为返回的是局部变量,出了作用域就会被释放
		{
			self temp = *this;
			++(*this);
			return temp;
		}
		self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}
		self operator--(int)
		{
			self temp = *this;
			--(*this);
			return temp;
		}
		Ref operator*() const    //如果迭代器是const类型,则Ref代表const T&,外部不可修改
		{
			return _node->_date;    
		}
		Ptr operator->() const   //返回当前节点_date部分的地址,在外部以指针的方式来使用
		{
			return &_node->_date;
		}


	};


	template<class T>   
	class list
	{
		typedef __list_node<T> node;
	public:
		typedef __list_iterator<T, T&, T*> iterator;   //这样传参就代表是可读可写的迭代器,即iterator是可读可写迭代器
		typedef __list_iterator<T, const T&, const T*> const_iterator; //这样传参就代表是只读迭代器,即const_iterator是只读迭代器
		list()
		{
			_head = new node();     //开辟一个头结点
			_head->_next = _head;
			_head->_prev = _head;
		}
		list(const list<T>& lt)
		{
			_head = new node();
			_head->_next = _head;
			_head->_prev = _head;
			const_iterator it = lt.begin();
			while (it != lt.end())
			{
				push_back(*it);
				++it;
			}
		}
		template<class InputIterator>
		list(InputIterator first, InputIterator last)
		{
			_head = new node();                        //这里不能写node _head = new node();   新创建出来的_node是个局部变量,并没有为成员变量初始化
			_head->_next = _head;
			_head->_prev = _head;
			while (first != last)
			{
				std::cout << *first << std::endl;
				push_back(*first);
				++first;
			}
		}


		//现代写法
		//list(const list<T>& lt)
		//{
		//	node* _head = new node();               //这里也要初始化一个头节点,否则交换之后,temp拿到的是一个没有初始化的头结点,出作用域析构时就会出错
		//	_head->_next = _head;
		//	_head->_prev = _head;
		//	list<T> temp(lt.begin(), lt.end());
		//	std::swap(_head, temp._head);
		//}




		list<T> operator=(list<T> lt)
		{
			std::swap(_head, lt._head);
			return *this;
		}

		~list()
		{
			clean();
			delete _head;
			_head = nullptr;
		}
		void clean()
		{
			iterator it = (*this).begin();
			while (it != (*this).end())
			{
				it = erase(it);                       //erase后迭代器会失效,要给迭代器重新赋值    
				//erase(it++);  与上面同理
			}
		}
		bool empty()
		{
			return begin() == end();
		}
		iterator begin() 
		{
			return _head->_next;   //iterator b(_head->next);   return b;
		}
		iterator end()
		{
			return _head;          //iterator b(_head);   return b;
		}
		const_iterator begin() const   //const修饰的是this指针,表示调用该函数的对象是被const修饰的
		{
			return _head->_next;   //iterator b(_head->next);   return b;
		}
		const_iterator end() const
		{
			return _head;          //iterator b(_head);   return b;
		}
		void push_back(const T& value)
		{
			node* tail = _head->_prev;
			node* newnode = new node(value);
			tail->_next = newnode;
			newnode->_prev = tail;
			newnode->_next = _head;
			_head->_prev = newnode;
			//insert(end(), value);
		}
		void push_front(const T& x)
		{
			insert(begin(), x);
		}
		iterator insert(iterator pos, const T& x)
		{
			node* newnode = new node(x);
			node* cur = pos._node;
			node* prev = cur->_prev;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;
			iterator ret(newnode);
			return ret;
		}
		void pop_back()
		{
			erase(begin());
		}
		void pop_front()
		{
			erase(--end());
		}
		iterator erase(iterator pos)
		{
			node* cur = pos._node;
			node* prev = cur->_prev;
			node* next = cur->_next;
			prev->_next = next;
			next->_prev = prev;
			delete cur;              //把要删除的空间释放掉,防止内存泄漏
			iterator ret(next);      //返回新位置的迭代器
			return ret;
		}
	private:
		node* _head;
	};
}

3. list中的迭代器失效问题

迭代器失效原因:因为list的迭代器是双向带头循环链表,插入节点并不会使迭代器失效,因为各节点的空间不是连续的,不存在增容。删除节点会导致迭代器失效,且只会使当前节点的迭代器失效,前面和后面的迭代器不受影响。
在这里插入图片描述
解决方法:删除后给带迭代器重新赋值即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值