C++——STL(list类)

news/2024/9/18 23:39:48 标签: c++, 开发语言

1.list的介绍

1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。

2. list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。

3. list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高效。

4. 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好

5. 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问

2.list的使用

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

list构造函数模拟实现:

//无参构造
List()
{
	CreateHead();
}
//构造
List(int n, const T& val = T())
{
	CreateHead();
	for (int i = 0; i < n; i++)
	{
		push_back(val);
	}
}
//参数为迭代器的构造
template<class iterator>
List(iterator first, iterator last)
{
	CreateHead();
	iterator it = first;
	while (it != last)
	{
		push_back(*it);
		++it;
	}
}
//拷贝构造
List(const List<T>& l)
{
	CreateHead();
	List<T> tmp(l.begin(), l.end());
	this->swap(tmp);
}

//析构
~List()
{
	clear();
	delete _head;
	_head = nullptr;
}

2.2 list iterator的使用

begin  + end :返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器

rbegin +  rend :返回第一个元素的reverse_iterator,即end位置,返回最后一个元素下一个位置的reverse_iterator,即begin位置

注意:

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

 list iterator的模拟实现:

template<class T,class Ref,class Ptr>
struct ListIterator
{
	typedef ListNode<T> Node;
	typedef ListIterator<T, Ref, Ptr> Self;
	//构造
	ListIterator(Node* node=nullptr)
		:_node(node)
	{}
	//迭代器的解引用
	Ref operator*()
	{
		return _node->_val;
	}

	Ptr operator->()
	{
		return &(_node->_val);
	}
	//迭代器的移动
	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& it) const
	{
		return _node != it._node;
	}

	bool operator==(const Self& it) const
	{
		return _node == it._node;
	}
	Node* _node; //迭代器本质是节点指针
};

2.3 list capacity

  • empty :检测list是否为空,是返回true,否则返回false
  • size :返回list中有效节点的个数

模拟实现:

// 容量相关
//size
size_t size() const
{
	Node* cur = _head->_next;
	size_t count = 0;
	while (cur != _head)
	{
		++count;
		cur = cur->_next;
	}
	return count;
}

bool empty() const
{
	return _head->_next == _head;
}

 2.4 list element access

  • front :返回list的第一个节点中值的引用
  • back :返回list的最后一个节点中值的引用

模拟实现:

//元素访问
T& front()
{
	return _head->_next->_val;
}

const T& front()const
{
	return _head->_next->_val;
}

T& back()
{
	return _head->_prev->_val;
}

const T& back()const
{
	return _head->_prev->_val;
}

 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中的有效元素
  • resize :改变list的size

 模拟实现:

//插入删除
void push_back(const T& data)
{
	insert(end(), data);
}

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

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

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

//insert
iterator insert(iterator pos, const T& val)
{
	Node* newnode = new Node(val);
	Node* cur = pos._node;
	newnode->_prev = cur->_prev;
	newnode->_next = cur;
	newnode->_prev->_next = newnode;
	cur->_prev = newnode;
	return iterator(newnode);
}

//erase
iterator erase(iterator pos)
{
	Node* cur = pos._node;
	Node* Ret = cur->_next;
	cur->_prev->_next = cur->_next;
	cur->_next->_prev = cur->_prev;
	delete cur;
	return iterator(Ret);
}

//swap
void swap(bit::List<T>& l)
{
	std::swap(_head, l._head);
}

//clear
void clear()
{
	Node* cur = _head->_next;

	while (cur != _head)
	{
		Node* next = cur->_next;
		delete cur;
		cur = next;
	}
	_head->_prev = _head->_next = _head;
}

//resize
void resize(size_t newsize, const T& data = T())
{
	int oldsize = size();
	if (newsize > oldsize)
	{
		while (oldsize < newsize)
		{
			push_back(data);
			++oldsize;
		}
	}
	else
	{
		while (oldsize > newsize)
		{
			pop_back();
			--oldsize;
		}
	}
}

2.6 list迭代器失效问题

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

 3.list与vector的对比

vector链接

vector

list

动态顺序表,一段连续空间

带头结点的双向循环链表

访

支持随机访问,访问某个元素效O(1)

不支持随机访问,访问某个元素效率O(N)

任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(N),插入时有可能需要增容,增容:开辟新空间,拷贝元素,释放旧空间,导致效率更低

任意位置插入和删除效率高,不需要搬移元素,时间复杂度为O(1)

底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高

底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低

原生态指针

对原生态指针(节点指针)进行封装

在插入元素时,要给所有的迭代器重新赋值,因为插入元素有可能会导致重新扩容,致使原来迭代器失效,删

除时,当前迭代器需要重新赋值否则会失效

插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响

使

需要高效存储,支持随机访问,不关心插入删除效率

大量插入和删除操作,不关心随机访问

4.模拟实现源码 

list.h

#pragma once

#include<iostream>

using namespace std;

namespace bit
{
	template<class T>
	struct ListNode
	{
		ListNode(const T& val=T())
			:_prev(nullptr)
			,_next(nullptr)
			,_val(val)
		{}

		ListNode* _prev;
		ListNode* _next;
		T _val;
	};

	template<class T,class Ref,class Ptr>
	struct ListIterator
	{
		typedef ListNode<T> Node;
		typedef ListIterator<T, Ref, Ptr> Self;
		//构造
		ListIterator(Node* node=nullptr)
			:_node(node)
		{}
		//迭代器的解引用
		Ref operator*()
		{
			return _node->_val;
		}

		Ptr operator->()
		{
			return &(_node->_val);
		}
		//迭代器的移动
		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& it) const
		{
			return _node != it._node;
		}

		bool operator==(const Self& it) const
		{
			return _node == it._node;
		}
		Node* _node; //迭代器本质是节点指针
	};

	template<class Iterator>
	struct ReverseListIterator
	{
		typedef typename Iterator::Ref Ref;
		typedef typename Iterator::Ptr Ptr;
		typedef ReverseListIterator<Iterator> Self;
		//构造
		ReverseListIterator(Iterator it)
			:_it(it)
		{}

		//迭代器的解引用
		Ref operator*()
		{
			Self tmp(_it);
			--tmp;
			return *tmp;
		}

		Ptr operator->()
		{
			Self tmp(_it);
			--tmp;
			return &(operator*());
		}

		//迭代器的移动
		Self operator++()
		{
			--_it;
			return *this;
		}

		Self operator++(int)
		{
			Self tmp(_it);
			--_it;
			return tmp;
		}

		Self operator--()
		{
			++_it;
			return *this;
		}

		Self operator--(int)
		{
			Self tmp(_it);
			++_it;
			return tmp;
		}

		//反向迭代器的比较
		bool operator!=(const Self& rit) const
		{
			return _it != rit._it;
		}

		bool operator==(const Self& rit) const
		{
			return _it == rit._it;
		}

		Iterator _it;
	};

	template<class T>
	class List
	{
		typedef ListNode<T> Node;
	public:
		//迭代器
		typedef ListIterator<T, T&, T*> iterator;
		typedef ListIterator<T, const T&, const T*> const_iterator;
		//反向迭代器
		typedef ReverseListIterator<iterator> reverse_iterator;
		typedef ReverseListIterator<const_iterator> const_reverse_iterator;

		//无参构造
		List()
		{
			CreateHead();
		}
		//构造
		List(int n, const T& val = T())
		{
			CreateHead();
			for (int i = 0; i < n; i++)
			{
				push_back(val);
			}
		}
		//参数为迭代器的构造
		template<class iterator>
		List(iterator first, iterator last)
		{
			CreateHead();
			iterator it = first;
			while (it != last)
			{
				push_back(*it);
				++it;
			}
		}
		//拷贝构造
		List(const List<T>& l)
		{
			CreateHead();
			List<T> tmp(l.begin(), l.end());
			this->swap(tmp);
		}

		//析构
		~List()
		{
			clear();
			delete _head;
			_head = nullptr;
		}
		/
		// 迭代器
		iterator begin()
		{
			return iterator(_head->_next);
		}
		const_iterator begin()const
		{
			return const_iterator(_head->_next);
		}
		iterator end()
		{
			return iterator(_head);
		}
		const_iterator end()const
		{
			return const_iterator(_head);
		}
		
		//反向迭代器
		reverse_iterator rbegin()
		{
			return reverse_iterator(end());
		}
		reverse_iterator rend()
		{
			return reverse_iterator(begin());
		}

		const_reverse_iterator rbegin()const
		{
			return const_reverse_iterator(end());
		}

		const_reverse_iterator rend()const
		{
			return const_reverse_iterator(begin());
		}
		//
		// 容量相关
		//size
		size_t size() const
		{
			Node* cur = _head->_next;
			size_t count = 0;
			while (cur != _head)
			{
				++count;
				cur = cur->_next;
			}
			return count;
		}
		bool empty() const
		{
			return _head->_next == _head;
		}
		void resize(size_t newsize, const T& data = T())
		{
			int oldsize = size();
			if (newsize > oldsize)
			{
				while (oldsize < newsize)
				{
					push_back(data);
					++oldsize;
				}
			}
			else
			{
				while (oldsize > newsize)
				{
					pop_back();
					--oldsize;
				}
			}
		}
		/
		//元素访问
		T& front()
		{
			return _head->_next->_val;
		}
		
		const T& front()const
		{
			return _head->_next->_val;
		}

		T& back()
		{
			return _head->_prev->_val;
		}

		const T& back()const
		{
			return _head->_prev->_val;
		}
		//
		//插入删除
		void push_back(const T& data)
		{
			insert(end(), data);
		}

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

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

		void pop_front()
		{
			erase(begin());
		}
		
		//insert
		iterator insert(iterator pos, const T& val)
		{
			Node* newnode = new Node(val);
			Node* cur = pos._node;
			newnode->_prev = cur->_prev;
			newnode->_next = cur;
			newnode->_prev->_next = newnode;
			cur->_prev = newnode;
			return iterator(newnode);
		}
		
		//erase
		iterator erase(iterator pos)
		{
			Node* cur = pos._node;
			Node* Ret = cur->_next;
			cur->_prev->_next = cur->_next;
			cur->_next->_prev = cur->_prev;
			delete cur;
			return iterator(Ret);
		}

		void clear()
		{
			Node* cur = _head->_next;

			while (cur != _head)
			{
				Node* next = cur->_next;
				delete cur;
				cur = next;
			}
			_head->_prev = _head->_next = _head;
		}

		void swap(bit::List<T>& l)
		{
			std::swap(_head, l._head);
		}
	private:
		void CreateHead()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
		}


		Node* _head;
	};
}


http://www.niftyadmin.cn/n/5664713.html

相关文章

八股(8)——Spring,SpringBoot

八股&#xff08;8&#xff09;——Spring&#xff0c;SpringBoot 基础1.Spring 是什么&#xff1f;特性&#xff1f;有哪些模块&#xff1f;Spring 有哪些特性呢&#xff1f; 2.Spring 有哪些模块呢&#xff1f;3.Spring 有哪些常用注解呢&#xff1f;Web 开发方面有哪些注解呢…

C++学习笔记之变量作用域

C学习笔记之变量作用域 https://www.runoob.com/cplusplus/cpp-variable-scope.html 在C程序中&#xff0c;通常有 3 个地方可以声明变量 在函数或者代码块当中&#xff0c;为局部变量在函数的参数定义中&#xff0c;为形式参数在所有函数的外部&#xff0c;为全局变量 作用域…

Hive性能优化高频面试题及答案

目录 高频面试题及答案1. 如何通过分区来优化Hive查询性能?2. 如何使用桶(Bucket)来优化Hive性能?3. 什么是Hive的`Map Side Join`?如何启用它?4. 如何通过压缩提高Hive的存储和查询性能?5. 什么是ORC文件格式?为什么它有助于提高性能?6. 如何通过调整Hive中的内存参数…

AI逻辑推理入门

参考数据鲸 (linklearner.com) 1. 跑通baseline 报名 申领大模型API 模型服务灵积-API-KEY管理 (aliyun.com) 跑通代码 在anaconda新建名为“LLM”的环境,并安装好相应包后,在jupyter notebook上运行baseline01.ipynb 2. 赛题解读 一般情况下,拿到一个赛题之后,我们需…

C++(学习)2024.9.18

目录 C基础介绍 C特点 面向对象的三大特征 面向对象与面向过程的区别 C拓展的非面向对象的功能 引用 引用的性质 引用的参数 指针和引用的区别 赋值 键盘输入 string字符串类 遍历方式 字符串与数字转换 函数 内联函数 函数重载overload 哑元函数 面向对象基…

python中Web API 框架

Python 中有几个非常流行的 Web API 框架&#xff0c;它们让你可以轻松地构建和部署高效的 Web API。下面我将为你介绍几个最受欢迎的 Python Web API 框架&#xff0c;及其使用方法和特点。 1. FastAPI FastAPI 是一个现代、快速&#xff08;非常高性能&#xff09;的 Web 框…

# 利刃出鞘_Tomcat 核心原理解析(十一)-- Tomcat 附加功能 WebSocket -- 3

利刃出鞘_Tomcat 核心原理解析&#xff08;十一&#xff09;-- Tomcat 附加功能 WebSocket – 3 一、Tomcat专题 - WebSocket - 案例 - OnMessage分析 1、WebSocket DEMO 案例 实现流程分析&#xff1a;OnMessage 分析 2、在项目 dzs168_chat_room 中&#xff0c;在 websocke…

2024年【四川省安全员A证】免费试题及四川省安全员A证试题及解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2024年【四川省安全员A证】免费试题及四川省安全员A证试题及解析&#xff0c;包含四川省安全员A证免费试题答案和解析及四川省安全员A证试题及解析练习。安全生产模拟考试一点通结合国家四川省安全员A证考试最新大纲及…