C++学习__09—List

【本节目标】
1. list 的介绍及使用
2. list 的深度剖析及模拟实现
3. list 与 vector 的对比

1. list 的介绍及使用


1.1 list 的介绍


list 的文档介绍
1. list 是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
2. list 的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
3. list 与 forward_list 非常相似:最主要的不同在于 forward_list 是单链表,只能朝前迭代,已让其更简单高效。
4. 与其他的序列式容器相比 (array,vector,deque),list 通常在任意位置进行插入、移除元素的执行效率更好。
5. 与其他序列式容器相比,list 和 forward_list 最大的缺陷是不支持任意位置的随机访问,比如:要访问 list 的第6个元素,必须从已知的位置 ( 比如头部或者尾部 ) 迭代到该位置,在这段位置上迭代需要线性的时间开销;list 还需要一些额外的空间,以保存每个节点的相关联信息 ( 对于存储类型较小元素的大 list 来说这可能是一个重要的因素 )

1.1 list 的使用


list 中的接口比较多,此处类似,只需要掌握如何正确的使用,然后再去深入研究背后的原理,已达到可扩展的能力。以下为 list 中一些常见的重要接口

1.2.1 list 的构造

构造函数constructor )接口说明
list ( )构造空的 list
list (size_type n, const value_type& val = value_type())构造的 list 中包含 n 个值为 val 的元素
list (const list& x)拷贝构造函数
list (InputIterator first, InputIterator last)用 [ first, last )区间中的元素构造 list

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

	// 以数组为迭代器区间构造l5
	int array[] = { 1,2,3,4 };
	list<int> l5(array, array + sizeof(array) / sizeof(int));

	// 用迭代器方式打印l5中的元素
	list<int>::iterator it = l5.begin();
	while (it != l5.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;

	// C++11范围for的方式遍历
	for (auto& e : l5)
	{
		cout << e << " ";
	}
	return 0;
}

代码运行结果:

1.2.2 list iterator 的使用


此处,大家可暂时将迭代器理解成一个指针,该指针指向 list 中的某个节点

函数声明接口说明
begin + end返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器
rbegin + rend返回第一个元素的 reverse_iterator ,即 end 位置,返回最后一个元素下一个位置的 reverse_iterator ,即 begin 位置

【注意】
1. begin 与end 为正向迭代器,对迭代器执行 ++ 操作,迭代器向后移动
2. rbegin(end) 与 rend(begin) 为反向迭代器,对迭代器执行 ++ 操作,迭代器向前移动

#include<iostream>
#include<List>
using namespace std;

void print_list(const list<int>& lt)
{
	// 注意这里调用的是list的 begin() const,返回ist的const iterator对象
	list<int>::const_iterator it = lt.begin();
	while (it != lt.end())
	{
		// *it=10; 编译不通过
		cout << *it << " ";
		it++;
	}
	cout << endl;
}

int main()
{
	int array[] = { 1,2,3,4 };
	list<int> lt(array, array + sizeof(array) / sizeof(int));

	// 使用正向迭代器正向list中的元素
	list<int>::iterator it = lt.begin();
	while (it != lt.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;

	// 使用反向迭代器逆向打印1ist中的元素
	list<int>::reverse_iterator rit = lt.rbegin();
	while (rit != lt.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;

	return 0;
}

代码运行结果:

1.2.3 list capacity
函数声明接口说明
empty检测 list 是否为空,是返回 true,否则返回 false
size返回 list 中有效节点的个数

1.2.4 list element access
函数声明接口说明
front返回list的第一个节点中值的引用
back返回list的最后一个节点中值的引用

1.2.5 list modifiers
函数声明接口说明
push_front

在 list 首元素前插入值为 val 的元素

pop_front删除 list 中第一个元素
push_back在 list 尾部插入值为 val 的元素
pop_back删除 list 中最后一个元素
insert在 list position 位置中插入值为 val 的元素
erase删除 list position 位置的元素
swap交换两个 list 中的元素
clear清空 list 中的有效元素

#include<iostream>
#include<List>
#include<vector>
using namespace std;

void print_list(list<int>& lt)
{
	for (auto& e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
}

// push_back / pop_back / push_front / pop_front
void test_list1()
{
	int array[] = { 1,2,3,4 };
	list<int> lt(array, array + sizeof(array) / sizeof(int));

	// 在list的尾部插入4,头部插入9
	lt.push_back(5);
	lt.push_front(0);
	print_list(lt);

	// 删除list尾部节点和头部节点
	lt.pop_back();
	lt.pop_front();
	print_list(lt);

}
int main()
{
	test_list1();
	return 0;
}

代码运行结果:

// insert / erase
void test_list2()
{
	int array[] = { 1,2,3,4 };
	list<int> lt(array, array + sizeof(array) / sizeof(int));

	// 获取链表中第二个节点
	auto pos = ++lt.begin();
	cout << *pos << endl;

	// 在pos前插入值为4的元素
	lt.insert(pos, 4);
	print_list(lt);

	// 在pos前插入5个值为5的元素
	lt.insert(pos, 5, 5);
	print_list(lt);

	// 在pos前插入[v.begin(),v.end)区间中的元素
	vector<int> v{ 7,8,9 };
	lt.insert(pos,v.begin(), v.end());
	print_list(lt);

	// 删除pos位置上的元素
	lt.erase(pos);
	print_list(lt);

	// 删除list中[begin,end)区间中的元素,即删除list中的所有元素
	lt.erase(lt.begin(), lt.end());
	print_list(lt);
}

代码运行结果:

// resize / swap / clear
void test_list3()
{
	// 用数组来构造list
	int array[] = { 1,2,3,4 };
	list<int> lt1(array, array + sizeof(array) / sizeof(int));
	print_list(lt1);
	
	list<int> lt2;
	lt2.push_back(5);
	lt2.push_back(6);
	lt2.push_back(7);
	lt2.push_back(8);

	// 交换l1和l2中的元素
	lt1.swap(lt2);
	print_list(lt1);
	print_list(lt2);

	// 将l2中的元素清空
	lt2.clear();
	cout << lt2.size() << endl;
}

代码运行结果:

list 中还有一些操作,需要用到时大家可参阅 list 的文档说明。


1.2.6 list 的迭代器失效


前面说过,此处大家可将迭代器暂时理解成类似于指针,迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为 list 的底层结构为带头结点的双向循环链表,因此在 list 中进行插入时是不会导致 list 的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响。

#include<iostream>
#include<list>
using namespace std;

void test_iterator0()
{
	int array[] = { 1,2,3,4 };
	list<int> lt1(array, array + sizeof(array) / sizeof(int));

	auto it = lt1.begin();
	while (it != lt1.end())
	{
		// erase()函数执行后,it所指向的节点已被删除,因此it无效,
		// 在下一次使用it时,必须先给其赋值
		lt1.erase(it);
		it++;
	}
}

int main()
{
	test_iterator0();
	return 0;
}

代码运行结果:

// 改正
void test_iterator1()
{
	int array[] = { 1,2,3,4 };
	list<int> lt1(array, array + sizeof(array) / sizeof(int));

	auto it = lt1.begin();
	while (it != lt1.end())
	{
		lt1.erase(it++);
		// it = lt1.erase(it);
	}
}

2. list 的模拟实现


2.1 模拟实现 list


要模拟实现 list,必须要熟悉 list 的底层结构以及其接口的含义,通过上面的学习,这些内容已基本掌握,现在我们来模拟实现 list。

有能力的实现一下下列函数接口:

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

namespace yut
{
	template<class T>
	struct __list_node
	{
		__list_node<T>* _next;
		__list_node<T>* _prev;
		T _data;

		__list_node(const T& x = T())
			:_data(x)
			, _next(nullptr)
			, _prev(nullptr)
		{ }
	};
	/*
	List 的选代器
	迭代器有两种实现方式,具体应根据容器底层数据结构实现
	1.原生态指针,比如: vector
	2.将原生态指针进行封装,因迭代器使用形式与指针完全相同,
	  因此在自定义的类中必须实现以下方法
	  1.指针可以解引用,迭代器的类中必须重载 operator*()
	  2.指针可以通过->访问其所指空间成员,迭代器类中必须重载oprator->()
	  3.指针可以++向后移动,迭代器类中必须重载operator++()与operator++(int)
	    至于operator--() / operator--(int)释放需要重载,根据具体的结构来抉择,
		双向链表可以向前移动,所以需要重载,如果是forward_list就不需要重载--运算符
	  4.迭代器需要进行是否相等的比较,因此还需要重载operator == ()与operator != ()
	*/
	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)
		{ }

		// *it
		T& operator*()
		{
			return _node->_data;
		}
		T* operator->()
		{
			return &_node->_data;
		}
		// ++it
		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}
		// it++
		Self operator++(T)
		{
			Self tmp(*this);
			// _node = _node->_next;
			++(*this);
			return tmp;
		}
		//--it
		Self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}
		// it--
		Self operator--(T)
		{
			Self tmp(*this);
			// _node = _node->_prev;
			--(*this);
			return tmp;
		}
		// it!=end()
		bool operator!=(const Self& it)
		{
			return _node != it._node;
		}
		bool operator==(const Self& it)
		{
			return _node == it._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 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();
		list(const list<T>& lt);
		list(size_t n, const T& val=T());
		list(iterator begin, iterator end);
		~list();
		iterator& operator=(const list<T>& lt);
		void clear();
		void push_back(const T& x);		// 尾插
		void pop_back()	;				// 尾删
		void push_front(const T& x);	// 头插
		void pop_front();				// 头删
		iterator insert(iterator pos, const T& x);
		iterator erase(iterator pos);
		iterator find(iterator begin, iterator end, const T& x); // 可有可无
	private:
		Node* _head;
	};
}

具体代码如下:

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

namespace yut
{
    // list的节点类
	template<class T>
	struct __list_node
	{
		__list_node<T>* _next;
		__list_node<T>* _prev;
		T _data;

		__list_node(const T& x = T())
			:_data(x)
			, _next(nullptr)
			, _prev(nullptr)
		{ }
	};
	/*
	List 的选代器
	迭代器有两种实现方式,具体应根据容器底层数据结构实现
	1.原生态指针,比如: vector
	2.将原生态指针进行封装,因迭代器使用形式与指针完全相同,
	  因此在自定义的类中必须实现以下方法
	  1.指针可以解引用,迭代器的类中必须重载 operator*()
	  2.指针可以通过->访问其所指空间成员,迭代器类中必须重载oprator->()
	  3.指针可以++向后移动,迭代器类中必须重载operator++()与operator++(int)
	    至于operator--() / operator--(int)释放需要重载,根据具体的结构来抉择,
		双向链表可以向前移动,所以需要重载,如果是forward_list就不需要重载--运算符
	  4.迭代器需要进行是否相等的比较,因此还需要重载operator == ()与operator != ()
	*/
	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)
		{ }

		// *it
		T& operator*()
		{
			return _node->_data;
		}
		T* operator->()
		{
			return &_node->_data;
		}
		// ++it
		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}
		// it++
		Self operator++(T)
		{
			Self tmp(*this);
			// _node = _node->_next;
			++(*this);
			return tmp;
		}
		//--it
		Self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}
		// it--
		Self operator--(T)
		{
			Self tmp(*this);
			// _node = _node->_prev;
			--(*this);
			return tmp;
		}
		// it!=end()
		bool operator!=(const Self& it)
		{
			return _node != it._node;
		}
		bool operator==(const Self& it)
		{
			return _node == it._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 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()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
		}
		list(const list<T>& lt)
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			for (auto e : lt)
			{
				push_back(e);
			}
		}
		list(size_t n, const T& val=T())
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			while (n--)
			{
				push_back(val);
			}
		}
		//template<class Iterator>
		//list(Iterator begin, Iterator end)
		//{
		//	_head = new Node;
		//	_head->_next = _head;
		//	_head->_prev = _head;
		//	while (begin != end)
		//	{
		//		push_back(*begin);
		//		begin++;
		//	}
		//}
		list(iterator begin, iterator end)
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			while (begin != end)
			{
				push_back(begin._node->_data);
				begin++;
			}
		}
		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}
		iterator& operator=(const list<T>& lt)
		{
			if (this != &lt)
			{
				clear();
				for (auto& e : lt)
				{
					push_back(e);
				}
			}
			return *this;
		}
		//iterator& operator=(list<T> lt)
		//{
		//	swap(_head, lt._head);
		//	return *this;
		//}
		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				erase(it++);
			}
		}
		void push_back(const T& x)		// 尾插
		{
			Node* tail = _head->_prev;
			Node* newnode = new Node;
			newnode->_data = x;

			tail->_next = newnode;
			newnode->_prev = tail;

			_head->_prev = newnode;
			newnode->_next = _head;
		}
		void pop_back()				// 尾删
		{
			Node* tail = _head->_prev;
			Node* prevtail = tail->_prev;

			prevtail->_next = _head;
			_head->_prev = prevtail;

			delete tail;
		}
		void push_front(const T& x)	// 头插
		{
			Node* newnode = new Node;
			newnode->_data = x;

			Node* front = _head->_next;
			_head->_next = newnode;
			front->_prev = newnode;
			newnode->_next = front;
			newnode->_prev = _head;
		}
		void pop_front()			// 头删
		{
			Node* front = _head->_next;
			Node* frontnext = front->_next;
			_head->_next = frontnext;
			frontnext->_prev = _head;
			delete front;
		}
		iterator insert(iterator pos, const T& x)
		{
			Node* newnode = new Node;
			newnode->_data = x;

			Node* cur = pos._node;
			Node* prev = cur->_prev;

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

			return 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 cur;
			return next;
		}
		//iterator find(iterator begin, iterator end, const T& x); // 可有可无
	private:
		Node* _head;
	};
}

2.2 对模拟的yut :: list 进行测试

#include"list.h"

template<class T>
void print_list(const yut::list<T>& lt)
{
	auto it = lt.begin();
	while (it != lt.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
}

void test_list0()
{
	yut::list<int> lt0;
	yut::list<int> lt1(4, 100);
	yut::list<int> lt2(lt1); 
	yut::list<int> lt3(lt0.begin(), lt0.end());

	print_list(lt0);
	print_list(lt1);
	print_list(lt2);
	print_list(lt3);
}

void test_list1()
{
	yut::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	print_list(lt);

	lt.pop_back();
	lt.pop_back();
	print_list(lt);

	lt.push_front(1);
	lt.push_front(2);
	lt.push_front(3);
	print_list(lt);

	lt.pop_front();
	lt.pop_front();
	print_list(lt);
}

void test_list2()
{
	int array[] = { 1,2,3,4,5,6,7,8,9 };
	yut::list<int> lt;
	for (auto& e: array)
	{
		lt.push_back(e);
	}

	auto pos = lt.begin();
	lt.insert(pos, 0);
	print_list(lt);

	++pos;
	lt.insert(pos, 2);
	print_list(lt);

	lt.erase(lt.begin());
	lt.erase(pos);
	print_list(lt);

	cout << *pos << endl;

	auto it = lt.begin();
	while (it != lt.end())
	{
		it = lt.erase(it);
	}
	print_list(lt);

}

int main()
{
	//test_list0();
	test_list1();
	//test_list2();

	return 0;
}

3.list 与 vector 的对比


vector 与 list 都是 STL 中非常重要的序列式容器,由于两个容器的底层结构不同,导致其特性以及应用场景不同,其主要不同如下:

vectorlist
底层结构动态顺序表,一段连续空间带头结点的双向循环链表
随机访问支持随机访问,访问某个元素效率O(1)不支持随机访问,访问某个元素效率O(N)
插入和删除任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(N),插入时有可能需要增容,增容:开辟新空间,拷贝元素,释放旧空间,导致效率更低任意位置插入和删除效率高,不需要搬移元素,时间复杂度为O(1)
空间利用率底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低
迭代器原生态指针对原生态指针(节点指针)进行封装
迭代器失效在插入元素时,要给所有的迭代器重新赋值,因为插入元素有可能会导致重新扩容,致使原来迭代器失效,删除时,当前迭代器需要重新赋值否则会失效插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响
使用场景需要高效存储,支持随机访问,不关心插入删除效率大量插入和删除操作,不关心随机访问

  • 10
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值