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;
}
相关推荐
blasit18 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20216 天前
信号量和信号
linux·c++