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;
}
相关推荐
iCxhust1 小时前
c# U盘映像生成工具
开发语言·单片机·c#
yangzhi_emo2 小时前
ES6笔记2
开发语言·前端·javascript
emplace_back3 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk3 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶3 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl3 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue3 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
收破烂的小熊猫~3 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
nananaij4 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm