【C++初阶】第十一篇——list(list常见接口的用法与介绍+list的模拟实现+list迭代器原理)

⭐️今天我先为大家介绍STL中的list容器,我会先介绍它的一些个常见接口以及用法,然后再模拟实现它,其中list的迭代器相比前两个容器的来说更为复杂,所以我会更加详细地介绍它,这样我们就能够比较深入地了解这个容器。
⭐️博客代码已上传至gitee:https://gitee.com/byte-binxin/cpp-class-code


🌏list的介绍

list的本质是一个带头的双向循环链表。

总结几点:

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

🌏list常见接口的介绍

🌲list的构造函数

在这里插入图片描述

  1. 无参构造: list()
  2. 用n个值为val的元素构造: list (size_type n, const value_type& val = value_type())
  3. 拷贝构造: list(const list& lt)
  4. 用一段区间的元素构造list: list (InputIterator first, InputIterator last)

实例演示

void TestList1()
{
	list<int> lt1;// 无参构造
	list<int> lt2(10, 5);// 用n个val构造一个list对象
	list<int> lt3(lt2);// 拷贝构造
	list<int> lt4(lt2.begin(), lt2.end());// 用一段区间的元素构造list

	cout << "lt1:";
	PrintList(lt1);

	cout << "lt2:";
	PrintList(lt2);

	cout << "lt3:";
	PrintList(lt3);

	cout << "lt4:";
	PrintList(lt4);
}

代码运行结果如下:
在这里插入图片描述

🌲list中迭代器

  1. .begin + end: 获取第一个数据位置的iterator/const_iterator, 获取最后一个数据的下一个位置
    的iterator/const_iterator
  2. rbegin + rend: 获取最后一个数据位置的reverse_iterator,获取第一个数据前一个位置的reverse_iterator
    在这里插入图片描述

🌲list的迭代器遍历

实例演示

void TestList2()
{
	list<int>lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);

	lt.push_front(0);
	lt.push_front(-1);
	lt.push_front(-2);

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

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

	list<int>::reverse_iterator rit = lt.rbegin();
	while (rit != lt.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}

代码运行结果如下:
在这里插入图片描述

🌲list的增删查改

在这里插入图片描述

  1. push_back: 尾插
  2. pop_back: 尾删
  3. push_front: 头插
  4. pop_front: 头删
  5. insert: 在pos位置插入一个元素
  6. erase: 删去pos位置的一个元素
  7. swap: 交换两个list中的元素
  8. clear: 清理list的有效元素

实例演示

void TestList3()
{
	list<int>lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_front(0);
	lt.push_front(-1);
	lt.push_front(-2);

	cout << "删除前:";
	PrintList(lt);

	lt.erase(lt.begin());
	cout << "删除后:";
	PrintList(lt);

	lt.insert(lt.begin(), 0);
	cout << "插入一个数据后:";
	PrintList(lt);
}

代码运行结果如下:
在这里插入图片描述

🌲list的大小和头尾元素的读取

  1. empty 判断容器是否为空
  2. size 获取容器有效节点的个数
  3. front 返回list的第一个节点的元素
  4. back 返回list的最后一个节点元素

🌏list迭代器失效

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

两种情况测试

  1. 插入
void TestList4()
{
	int arr[] = { 1,2,3,4,5 };
	list<int> lt(arr, arr + sizeof(arr) / sizeof(arr[0]));

	list<int>::iterator it = lt.begin();

	lt.insert(it, 3);
}

代码运行结果如下:
在这里插入图片描述

  1. 删除
void TestList4()
{
	int arr[] = { 1,2,3,4,5 };
	list<int> lt(arr, arr + sizeof(arr) / sizeof(arr[0]));

	list<int>::iterator it = lt.begin();

	while (it != lt.end())
	{
		lt.erase(it);
		++it;
	}
}

代码运行结果如下:
在这里插入图片描述
总结: 插入数据不会导致迭代器失效,删除数据会导致迭代器失效。相比vector容器,vector容器插入数据是会导致迭代器失效,因为vector涉及增容问题,而list却不存在增容问题,所以迭代器指向的位置是有效的。删除数据会导致迭代器指向的位置是无效的,所以迭代器会失效。

修改后的代码如下:

void TestList4()
{
	int arr[] = { 1,2,3,4,5 };
	list<int> lt(arr, arr + sizeof(arr) / sizeof(arr[0]));

	list<int>::iterator it = lt.begin();

	//lt.insert(it, 3);
	while (it != lt.end())
	{
		it = lt.erase(it);
	}
}

🌏list的模拟实现

🍯list的整体框架

list是由节点组成,所以定义一个节点的类,然后list的类中成员只需要一个头结点的指针即可。

template<class T>
struct __list_node
{
	__list_node<T>* _prev;
	__list_node<T>* _next;
	T _data;
	__list_node(const T& x = T())
		:_next(nullptr)
		, _prev(nullptr)
		, _data(x)
	{}
};
template<class T>
class list
{
	typedef __list_node<T> Node;
public:
private:
	Node* _head;
};

🍯list的构造函数

构造函数要做的任务就是开一个头结点,所以我们可以封装出一个具体的函数来实现创建头结点的这个过程。

创建头结点:

void CreatHead()
{
	_head = new Node;
	_head->_next = _head;
	_head->_prev = _head;
}

构造函数的实现:

list()
{
	CreatHead();
}

🍯list的迭代器的实现

list相比vector的迭代器而言,不再是一个简单的指针,它相对而言更复杂一些,list的迭代器为了实现一些简单的功能,我们把它封装成了一个类。看下面源码实现:

在这里插入图片描述

我们自己来模拟实现一下简单的。
迭代器的小框架(里面有一个成员变量——节点指针)

struct __list_iterator
{
	typedef __list_node<T> Node;
	__list_iterator(Node* node = nullptr)
		:_node(node)
	{}
	Node* _node;
}

由于迭代器分普通迭代器和const 迭代器,为了不造成代码冗余,我们设计出来三个模板参数,根据传入的模板参数确定是那种迭代器。
在这里插入图片描述

迭代器的实现

// __list_iterator<T, T&, T*>  ->  普通迭代器
// __list_iterator<T, const T&, const T*>  ->  const迭代器
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 = nullptr)
		:_node(node)
	{}
	__list_iterator(const Self& l)
		:_node(l._node)
	{}
	// *it  T&
	Ref operator*()
	{
		return _node->_data;
	}
	// it->  T*
	Ptr operator->()
	{
		return &_node->_data;
	}
	Self& operator++()
	{
		_node = _node->_next;
		return *this;
	}
	Self& operator--()
	{
		_node = _node->_prev;
		return *this;
	}
	Self operator++(int)
	{
		Self tmp(*this);
		//_node = _node->_next;
		++(*this);

		return tmp;
	}
	Self operator--(int)
	{
		Self tmp(*this);
		//_node = _node->_prev;
		--(*this);

		return tmp;
	}
	Self operator+(int count)
	{
		Self tmp(*this);
		while (count--)
		{
			++tmp;
		}

		return tmp;
	}
	Self operator-(int count)
	{
		Self tmp(*this);
		while (count--)
		{
			--tmp;
		}

		return tmp;
	}
	bool operator!=(const Self& it)
	{
		return _node != it._node;
	}
};

我们还要在list里面做这样一个操作(堆两种迭代器进行重命名,方便我们认识):

typedef __list_iterator<T, T&, T*> iterator;// 普通迭代器
typedef __list_iterator<T, const T&, const T*> const_iterator;// const迭代器

list内部begin()和end()的实现(普通迭代器调用前两个,const迭代器调用后两个)

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);
}

🍯list的增删查改的实现

这里几个接口其实我们再之前数据结构的时候都实现过,比较简单

  1. push_back 这里的操作和我们之前数据结构中实现双链表的操作是一样的,我们只需要先开一个节点,然后再改变几个节点指针的指向就好了
void push_back(const T& x)
{
	Node* newnode = new Node(x);
	Node* tail = _head->_prev;

	tail->_next = newnode;
	newnode->_prev = tail;
	newnode->_next = _head;
	_head->_prev = newnode;
}
  1. pop_back
void pop_back()
{
	assert(_head != _head->_next);
	Node* tail = _head->_prev;
	Node* prevTail = tail->_prev;
	delete tail;
	tail = prevTail;

	tail->_next = _head;
	_head->_prev = tail;
}
  1. push_front
void push_front(const T& x)
{
	Node* newnode = new Node(x);
	Node* firstNode = _head->_next;

	_head->_next = newnode;
	newnode->_prev = _head;
	newnode->_next = firstNode;
	firstNode->_prev = newnode;
}
  1. pop_front
void pop_front()
{
	assert(_head->_next != _head);
	Node* firstNode = _head->_next;
	Node* secondNode = firstNode->_next;

	delete firstNode;
	firstNode = nullptr;

	_head->_next = secondNode;
	secondNode->_prev = _head;
}
  1. insert 在pos位置插入元素,首先要检测pos位置的有效性
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;
}

注意,为了提高代码的复用性,push_front和push_back都可以复用insert

void push_back(const T& x)
{
	insert(end(), x);
}
void push_front(const T& x)
{
	insert(begin(), x);
}
  1. erase 删去pos位置的元素,同样要判断list是否为空
iterator erase(iterator pos)
{
	assert(_head->_next != _head);
	assert(pos != end());

	Node* node = pos._node;
	Node* prev = node->_prev;
	Node* next = node->_next;

	delete node;
	node = nullptr;

	prev->_next = next;
	next->_prev = prev;

	return iterator(next);
}

同样地,为了提高代码的复用性,pop_front和pop_back都可以复用erase

void pop_back()
{
	erase(end() - 1);
}
void pop_front()
{
	erase(begin());
}
  1. front 返回第一个节点的元素
T front()
{
	assert(_head->_next != _head);
	return _head->_next->_data;
}
  1. back 返回最后一个节点的元素
T back()
{
	assert(_head->_next != _head);
	return _head->_prev->_data;
}

🍯list中的析构函数和clear

  1. clear 通过迭代器遍历,一个一个的删除节点
void clear()
{
	iterator it = begin();
	while (it != end())
	{
		it = erase(it);
	}
}
  1. 析构函数 可以先调用clear函数清理空间,然后再delete掉头结点
~list()
{
	clear();
	delete _head;
	_head = nullptr;
}

🍯拷贝构造和operator=赋值重载

  1. 拷贝构造
list(const list<T>& lt)
{
	CreatHead();
	/*const_iterator it = lt.begin();
	while (it != lt.end())
	{
		push_back(*it);
		++it;
	}*/
	for (auto e : lt)
		push_back(e);
}
  1. operator= 直接利用swap和形参交换,形参会自己调用析构函数清理空间
list<T>& operator=(list<T> lt)
{
	if (this != &lt)// 防止自己给自己赋值
	{
		swap(lt);
	}

	return *this;
}

swap函数实现如下:

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

🌏list和vector对比

这里对比和之前数据结构中顺序表和单链表的对比是一样的,如下:

vectorlist
底层结构动态顺序表,一段连续的空间带头双向循环链表
随机访问支持,时间复杂度是O(1)不支持,时间复杂度是O(N)
插入和删除效率低,时间复杂度是O(N)效率高,时间复杂度是O(1)
空间利用率底层是连续的空间,不容易造成内存碎片化底层动图开辟,小结点容易造成内存碎片,空间利用率低
迭代器原生指针堆原生态指针进行封装
迭代器失效插入和删除都会造成,所以最后每次操作后堆迭代器重新赋值插入数据不会,删除数据会造成迭代器失效
使用场景需要高存储效率,支持随机访问,不关心插入删除效率大量插入删除操作,不关心随机访问

🌐总结

list的所有内容就介绍到这里,喜欢的话,欢迎点赞、关注和收藏,感谢大家支持~
在这里插入图片描述

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆呆兽学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值