C++STL库中的list

news2024/9/23 15:31:07


文章目录

  • list的介绍及使用
  • list的常用接口
  • list的模拟实现
  • list与vector的对比

一、list的介绍及使用

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

二、list的常用接口

1.list的构造函数

default (1)
list();explicit list (const allocator_type& alloc);

  构造一个没有元素的空容器。

fill (2)
explicit list (size_type n, const allocator_type& alloc = allocator_type());         

list (size_type n, const value_type& val, const allocator_type& alloc = allocator_type());

构造一个包含n个元素的容器。每个元素都是val。

range (3)
template <class InputIterator>  
list (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());

构造一个包含与范围[first,last]一样多的元素的容器,每个元素都以相同的顺序从该范围中的相应元素构造而成。

copy (4)
list (const list& x);
list (const list& x, const allocator_type& alloc);

以相同的顺序构造一个包含x中每个元素的副本的容器。

move (5)
list (list&& x);list (list&& x, const allocator_type& alloc);

 右值引用构造

initializer list (6)
list (initializer_list<value_type> il, const allocator_type& alloc = allocator_type());

构造一个通过初始化列表的方式

#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

    // 以数组为迭代器区间构造l5
    int array[] = { 16,2,77,29 };
    std::list<int> l5(array, array + sizeof(array) / sizeof(int));

    // 列表格式初始化C++11
    std::list<int> l6{ 1,2,3,4,5 };

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

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

    std::cout << std::endl;


	return 0;
}

2.list iterator的使用

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

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

#include <iostream>
#include <list>

int main()
{
	std::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);

	for (auto it = lt.begin(); it != lt.end(); it++)
		std::cout << *it << " ";
	std::cout << std::endl;

	for (auto x : lt)
		std::cout << x << " ";
	std::cout << std::endl;
	return 0;
}

3.list相关容量操作

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

#include <iostream>
#include <list>

int main()
{
	std::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);

	std::cout << lt.size() << std::endl;
	std::cout << lt.empty() << std::endl;
	return 0;
}

4.list相关访问操作

函数声明                                                                                  接口说明
front                                                                  返回list的第一个节点中值的引用
back                                                                  返回list的最后一个节点中值的引用
#include <iostream>
#include <list>

int main()
{
	std::list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);

	std::cout << lt.front() << std::endl;
	std::cout << lt.back() << std::endl;
	return 0;
}

5.list相关修改操作

函数声明                                                                                接口说明
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 <vector>
#include <list>

// list迭代器的使用
// 注意:遍历链表只能用迭代器和范围for
void PrintList(const std::list<int>& l)
{
    // 注意这里调用的是list的 begin() const,返回list的const_iterator对象
    for (std::list<int>::const_iterator it = l.begin(); it != l.end(); ++it)
    {
        std::cout << *it << " ";
        // *it = 10; 编译不通过
    }

    std::cout << std::endl;
}

// list插入和删除
// push_back/pop_back/push_front/pop_front
void TestList3()
{
    int array[] = { 1, 2, 3 };
    std::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 TestList4()
{
    int array1[] = { 1, 2, 3 };
    std::list<int> L(array1, array1 + sizeof(array1) / sizeof(array1[0]));

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

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

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

    // 在pos前插入[v.begin(), v.end)区间中的元素
    std::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 TestList5()
{
    // 用数组来构造list
    int array1[] = { 1, 2, 3 };
    std::list<int> l1(array1, array1 + sizeof(array1) / sizeof(array1[0]));
    PrintList(l1);

    // 交换l1和l2中的元素
    std::list<int> l2;
    l1.swap(l2);
    PrintList(l1);
    PrintList(l2);

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

int main()
{
    TestList3();
    TestList4();
    TestList5();
	return 0;
}

6.list容器相关独特操作

 splice                                     将元素从一个链表转移到另一个链表(公共成员函数)



 remove                                  删除具有特定值的元素(公共成员函数)

remove_if                                 删除满足条件的元素(公共成员函数模板)

unique                                                  删除重复值(公共成员函数)

mergemerge                                   合并已排序的列表(公共成员功能)


sort                                                对容器中的元素排序(公共成员函数)

reverse                                     颠倒元素的顺序(公共成员函数)

三、list的模拟实现

1.list的节点结构

template<class T>
	struct list_node
	{
		T _data;//数据域
		list_node<T>* _prev;//前驱指针
		list_node<T>* _next;//后继指针

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

2.list的常用接口模拟

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;

		const_iterator begin()const;

		const_iterator end()const;

		iterator begin();

		iterator end();

		list();
        template<class InputIterator>
        list(InputIterator first,InputIterator last);
        list(const list<T>& lt);
        list<T>& operator=(list<T> lt);
        ~list();
        
        size_t size();
        bool empty();

		void push_back(const T& val);

		void push_front(const T& val);

		iterator insert(iterator pos, const T& x);

		iterator erase(iterator pos);

		void pop_back();

		void pop_front();
        
        void clear();
	private:
		Node* _head;
	};

3.list的迭代器

1.迭代器相关结构组成

	// 像指针一样的对象
	template<class T, class Ref, class Ptr>
	struct __list_iterator
	{
		typedef list_node<T> Node;
		typedef __list_iterator<T, Ref, Ptr> iterator;

		typedef bidirectional_iterator_tag iterator_category;
		typedef T value_type;
		typedef Ptr pointer;
		typedef Ref reference;
		typedef ptrdiff_t difference_type;


		Node* _node;

		__list_iterator(Node* node)
			:_node(node)
		{}

		bool operator!=(const iterator& it) const;

		bool operator==(const iterator& it) const;

		Ref operator*();
 
		Ptr operator->();

		iterator& operator++();

		iterator operator++(int);
		
		iterator& operator--();

		iterator operator--(int);
	};

2.迭代器结构实现

template<class T,class Ref,class Ptr>
	struct __list_iterator
	{
		typedef list_node<T> Node;
		typedef __list_iterator<T, Ref, Ptr> iterator;

		typedef  std::bidirectional_iterator_tag iterator_category;
		typedef T value_type;
		typedef Ptr pointer;
		typedef Ref reference;
		typedef ptrdiff_t difference_type;

		Node* _node;

		__list_iterator(Node* node)
			:_node(node)
		{};

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

		bool operator==(const iterator& it)const
		{
			return _node == it._node;
		}

		Ref operator*()
		{
			return _node->_data;
		}

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

		iterator& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		iterator operator++(int)
		{
			iterator tmp(*this);
			_node = _node->_next;
			return tmp;
		}

		iterator& operator--()
		{
			_node = _node->_prev;
			return *this;
		}

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

4.list的成员函数

1.list的构造函数

// 默认构造函数
list()
{
    // 构造头节点,自己指向自己
    _head = new Node;
    _head->_prev = _head;
    _head->_next = _head;
}

// 用迭代器区间初始化[first,last)
template<class InputIterator>
list(InputIterator first, InputIterator last)
    :_head(new Node) 
{
	_head->_prev = _head;
	_head->_next = _head;
        

	while (first != last)
	{
		push_back(*first);
		first++;
	}
}

2.list的拷贝构造函数

//拷贝构造函数(深拷贝)
// lt2(lt1)
list(const list<T>& lt)
    :_head(new Node) 
{
    _head->_prev = _head;
    _head->_next = _head;
 
    for (const auto& e : lt)
    {
    	push_back(e);
    }
}

// 拷贝构造函数(深拷贝)
list(const list<T>& lt)
    :_head(new Node) 
{
    _head->_prev = _head;
    _head->_next = _head;

	list<T> tmp(lt.begin(), lt.end());
	std::swap(_head, tmp._head); 
}

3.list的赋值运算符重载函数

//深拷贝
list<T>& operator=(const list<T>& lt)
{
    if (this != &lt) 
    {

        clear();


        for (const auto& e : lt)
        {
            push_back(e);
        }
    }

    return *this; 
}


list<T>& operator=(list<T> lt) 
{
    std::swap(_head, lt._head);

    return *this; 
}

4.list的析构函数

~list()
{
	//方法一
    Node* cur = _head->_next;

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

        delete cur; 

        cur = next;
    }

    delete _head; 
    _head = nullptr;
	

    //方法二:复用 clear 函数的代码

    clear();
    delete _head;
    _head = nullptr;
}

5.list其他相关结构函数

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

		void push_back(const T& x)
		{
			//Node* tail = _head->_prev;
			//Node* newnode = new Node(x);

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

			insert(end(), x);
		}

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

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

			Node* newnode = new Node(x);

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

			return iterator(newnode);
		}

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

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

		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 iterator(next);
		}

5.list的迭代器失效

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

void testlistiterator1()
{
	int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	std::list<int> l(array, array + sizeof(array) / sizeof(array[0]));
	auto it = l.begin();
	while (it != l.end())
	{
		// erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值
		it = l.erase(it);
		it++;
	}
}

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

四、listvector的对比

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/798778.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

数据库对象

二十、数据库对象-视图 二十一、数据库对象-索引 age字段没有索引&#xff0c;查找需要扫描全表&#xff1a; name字段做了唯一索引&#xff0c;查找一次&#xff1a; 二十二、数据库对象-事务 事务的隔离级别和问题&#xff1a;

(链表) 剑指 Offer 52. 两个链表的第一个公共节点 ——【Leetcode每日一题】

❓剑指 Offer 52. 两个链表的第一个公共节点 难度&#xff1a;简单 输入两个链表&#xff0c;找出它们的第一个公共节点。 如下面的两个链表&#xff1a; 在节点 c1 开始相交。 示例 1&#xff1a; 输入&#xff1a;intersectVal 8, listA [4,1,8,4,5], listB [5,0,1,8…

三星GalaxyWatch放弃iOS:无法给用户一致的体验,还不如“丢掉”

昨晚&#xff0c;三星发布了全新的Galaxy Watch 6系列智能手表。然而&#xff0c;对于苹果手机用户来说&#xff0c;这个消息可能并不那么重要。因为从2021年开始&#xff0c;三星决定转向Wear OS系统&#xff0c;并计划在Galaxy Watch 4及以后的新款智能手表上采用该系统&…

Python基础语法第八章之使用库

目录 一、使用库 二、标准库 2.1认识标准库 2.2使用 import 导入模块 2.3第三方库 2.3.1认识第三方库 2.3.2使用 pip 一、使用库 库 就是是别人已经写好了的代码, 可以让我们直接拿来用. 按照库的来源, 可以大致分成两大类 标准库: Python 自带的库. 只要安装了 Pytho…

JavaEE——SpringMVC中的常用注解

目录 1、RestController &#xff08;1&#xff09;、Controller &#xff08;2&#xff09;、ResponseBody 2、RequestMappping &#xff08;1&#xff09;、定义 &#xff08;2&#xff09;、使用 【1】、修饰方法 【2】、修饰类 【3】、指定方法类型 【4】、简化版…

朝花夕拾思维导图怎么画?看看这种绘制方法

朝花夕拾思维导图怎么画&#xff1f;绘制思维导图的好处有很多&#xff0c;首先它可以帮助人们更好地组织和管理知识&#xff0c;提高工作效率和学习效果。其次&#xff0c;绘制思维导图可以帮助人们更好地记忆知识点和理解知识点。总之&#xff0c;绘制思维导图可以帮助人们更…

字符串函数介绍应用

字符串 1.前言 C语言中对字符和字符串的处理很是频繁&#xff0c;但是C语言本身是没有字符串类型的&#xff0c;字符串通常放在 常量字符串中或者字符数组中。 字符串常量适合于那些对他不做修改的函数。 2.库函数及其模拟实现 2.1 strlen函数 size_t strlen ( const char *…

机器学习深度学习——多层感知机的简洁实现

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位即将上大四&#xff0c;正专攻机器学习的保研er &#x1f30c;上期文章&#xff1a;机器学习&&深度学习——多层感知机的从零开始实现 &#x1f4da;订阅专栏&#xff1a;机器学习&&深度学习 希望文章对你…

东南大学轴承故障诊断(Python代码,CNN模型,适合复合故障诊断研究)

运行代码要求&#xff1a; 代码运行环境要求&#xff1a;Keras版本>2.4.0&#xff0c;python版本>3.6.0 本次实验主要是在两种不同工况数据下&#xff0c;进行带有复合故障的诊断实验&#xff0c;没有复合故障的诊断实验。 实验结果证明&#xff0c;针对具有复合故障的…

Linux系统MySQL数据库的备份及应用

本节主要学习了MySQL数据库的备份&#xff1a;概念&#xff0c;数据备份的重要性&#xff0c;造成数据丢失的原因&#xff0c;备份的类型&#xff0c;常见的备份方法&#xff0c;实例与应用等。 目录 一、概述 二、数据备份的重要性 三、造成数据丢失的原因 四、备份类型 …

AMEYA360:ROHM罗姆授权代理有哪些?

罗姆(ROHM)株式会社是全球知名的半导体厂商之一&#xff0c;总部所在地设在日本京都市&#xff0c;1958年作为小电子零部件生产商在京都起家的罗姆&#xff0c;于1967年和1969年逐步进入了晶体管、二极管领域和IC等半导体领域。2年后的1971年&#xff0c;罗姆作为第一家进入美国…

K8S故障排查

故障现象&#xff1a;部署pod时&#xff0c;报错没发调度到节点。 排查步骤&#xff1a; 1、查看集群的状态 [rootk8s-master1 nginx]#kubectl get nodes2、查看k8s组件的状态-kubelet&#xff0c;kube-apiservice 3、查看docker的Cgroup driver和k8s的Cgroup driver类型&…

list源码分析,基于c++ 和vs2019,cpp20标准

list源码分析,基于c 和vs2019&#xff0c;cpp20标准。结构确实如图&#xff0c;双向环形链表。

Qt C++实现Excel表格的公式计算

用Qt的QTableViewQStandardItemModelQStyledItemDelegate实现类似Excel表格的界面&#xff0c;在parser 模块中提供解析表格单元格输入的公式。单元格编辑结束后按回车进行计算和更新显示。 效果如下&#xff1a; 支持的公式计算可以深度嵌套&#xff0c;目前parser模块中仅提…

【C语言day08】

int n5; int a[n][n2] 数组定义下角标不能为变量 注&#xff1a;C99标准中支持了使用变量本题考查的是二维数组的元素访问&#xff0c;A选项是 正确的&#xff0c;X[i]就是第i行的数组名&#xff0c;数组名表示首元素的地址&#xff0c;X[i]表示第i行的第一个元素的地址&#…

【开源项目】智慧高铁站~经典开源项目数字孪生智慧高铁站——开源工程及源码

广州南站工程和源码免费赠送&#xff0c;人人都可探索其魅力&#xff01; 项目介绍 广州南站&#xff0c;中国最大的综合交通枢纽之一&#xff0c;处于广州市珠江新城中轴线上&#xff0c;是广州南沙新区的门户之一。利用数字孪生技术&#xff0c;通过3Dmaxs技术实现数据和场景…

MySQL基础扎实——MySQL中各种数据类型之间的区别

在MySQL中&#xff0c;有各种不同的数据类型可供选择来存储不同类型的数据。下面是一些常见的数据类型以及它们之间的区别&#xff1a; 整数类型&#xff1a; TINYINT&#xff1a;1字节&#xff0c;范围为-128到127或0到255&#xff08;无符号&#xff09;。SMALLINT&#xff1…

Hadoop的伪分布式安装方法

实验环境&#xff1a; 操作系统&#xff1a;Linux (Ubuntu 20.04.5) Hadoop版本&#xff1a;3.3.2 JDK版本&#xff1a;1.8.0_162 &#xff08;1&#xff09;创建 hadoop 用户&#xff08;使用 /bin/bash 作为 Shell&#xff09;、设置密码&#xff08;建议简单&#xff09…

YOLO算法改进指南【中阶改进篇】:9.添加S2-MLPv2注意力机制

一、理论知识 S2MLPv2 依是百度提出的用于视觉的空间位移 MLP 架构,其作者以及顺序与 S2MLP 一模一样,其论文为 S2-MLPv2: Improved Spatial-Shift MLP Architecture for Vision。S2MLPv2 的修改点主要在于三处:金字塔结构(参考 ViP)、分三类情况进行考虑(参考 ViP)、使…

注解和反射02--Java反射

反射 动态和静态语言获取反射对象Java反射机制提供的功能Java反射优缺点反射相关的主要API 动态和静态语言 要学习反射&#xff0c;首先我们需要了解一下静态和动态语言。 动态语言&#xff1a;是一类在运行时可以改变其结构的语言&#xff1a;例如新的函数、对象、甚至代码可…