list容器

1. list 的介绍

list 是序列容器,允许在序列中的任何位置进行O(1)时间复杂度的插入和删除操作以及双向迭代。

list 容器实现为带头结点双向链表,双向链表可以将它们包含的每个元素存储在不同且不相关的存储位置。

2. list 的使用

2.1 构造函数

  1. list()

构造一个空的list容器。

  1. list(const list& x)

用一个 list 容器去构造另一个 list 容器。

  1. list(size_t n, int x)

用 n 个元素去构造一个 list 。

  1. list(Inputiterator first, Inputiterator last)

用一段迭代器区间去构造 list 容器。

  1. list(initializer_list)

C++11新添加的构造函数,用一段列表去构造 list 容器。

cpp 复制代码
#include<list>
#include<iostream>

using namespace std;

int main()
{
	list<int> l1;
	for (auto& e : l1)
	{
		cout << e << ' ';
	}
	cout << endl;

	list<int> l2(5, 1);
	for (auto& e : l2)
	{
		cout << e << ' ';
	}
	cout << endl;

	list<int> l3(l2);
	for (auto& e : l3)
	{
		cout << e << ' ';
	}
	cout << endl;

	list<int> l4(l3.begin(), l3.end());
	for (auto& e : l4)
	{
		cout << e << ' ';
	}
	cout << endl;
	
	list<int> l5 = { 1,2,3,4 };
	for (auto& e : l5)
	{
		cout << e << ' ';
	}
	cout << endl;

	return 0;
}

2.2 list 迭代器

  1. begin() + end()

返回第一个元素的迭代器和最后一个元素下一个位置的迭代器。

  1. rbegin() + rend()

和正向迭代器刚好相反,返回最后一个元素位置的迭代器和第一个元素前面一个元素的位置。

cpp 复制代码
#include<list>
#include<iostream>

using namespace std;

int main()
{
	list<int> l1 = { 1,2,3,4 };
	
	list<int>::iterator it1 = l1.begin();
	while (it1 != l1.end())
	{
		cout << *it1 << ' ';
		it1++;
	}
	cout << endl;

	list<int>::reverse_iterator it2 = l1.rbegin();
	while (it2 != l1.rend())
	{
		cout << *it2 << ' ';
		it2++;
	}
	cout << endl;

	return 0;
}

2.3 list 的一些常用接口介绍

  1. push_back(int x)

尾插一个元素。

  1. pop_back()

尾删一个元素。

  1. insert(iterator pos, int x)

在指定迭代器的前一个元素后面插入元素。

  1. size()

计算元素大小。

  1. front()

返回第一个元素。

  1. back()

返回最后一个元素。

  1. erase(iterator pos)

删除迭代器位置元素。

cpp 复制代码
#include<list>
#include<iostream>

using namespace std;

int main()
{
	list<int> l1 = { 1,2,3,4 };

	l1.push_back(5);
	for (auto& e : l1)
	{
		cout << e << ' ';
	}
	cout << endl;

	l1.pop_back();
	for (auto& e : l1)
	{
		cout << e << ' ';
	}
	cout << endl;

	l1.insert(l1.begin(), 10);
	for (auto& e : l1)
	{
		cout << e << ' ';
	}
	cout << endl;

	cout << l1.size() << endl;
	cout << l1.front() << endl;
	cout << l1.back() << endl;

	l1.erase(l1.begin());
	for (auto& e : l1)
	{
		cout << e << ' ';
	}
	cout << endl;

	return 0;
}
相关推荐
昵称画1 小时前
交接班记录电子化:三班之间的信息不漏
开发语言·数据库·人工智能·低代码·php
“AI国潮设计-小江”1 小时前
【AIGC实战】Python+SDXL批量生成“潮汕英歌舞不倒翁”IP | 角色一致性与多场景融合方案,附完整代码
开发语言·人工智能·python·prompt·aigc
传奇开心果编程1 小时前
【Rust入门练中学】第6课:结构体与方法
开发语言·rust·结构体·编程语言理论·结构体方法·编程通用语言
code tsunami2 小时前
【无标题】
开发语言·python
CodeGL2 小时前
10、Python基础之进程和线程
开发语言·python
hetao17338373 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
TechWayfarer3 小时前
PHP漏洞被利用,怎么揪出攻击IP?
开发语言·python·tcp/ip·网络安全·php
王老师青少年编程4 小时前
2025年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
卡卡~~5 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
qq_406981035 小时前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust