【C++】STL详解(五)—— list的介绍及使用

在这里插入图片描述

​📝个人主页:@Sherry的成长之路
🏠学习社区:Sherry的成长之路(个人社区)
📖专栏链接:C++学习
🎯长路漫漫浩浩,万事皆有期待

上一篇博客:【C++】C++STL详解(四)—— vector的模拟实现

list的介绍

1.list是一种可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。它的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立结点当中,在结点中通过指针指向其前一个元素和后一个元素。
2.list与forward_list非常相似,最主要的不同在于forward_list是单链表,只能进行单方向迭代。与其他容器相比,list通常在任意位置进行插入、删除元素的执行效率更高
3.list和forward_list最大的缺陷是不支持在任意位置的随机访问,其次,list还需要一些额外的空间,以保存每个结点之间的关联信息。

list的使用

list的定义方式

一: 构造一个某类型的空容器。

list<int> lt1; //构造int类型的空容器

二: 构造一个含有n个val的某类型容器。

list<int> lt2(10, 2); //构造含有10个2的int类型容器

三: 拷贝构造某类型容器的复制品。

list<int> lt3(lt2); //拷贝构造int类型的lt2容器的复制品

四: 使用迭代器拷贝构造某一段内容。

string s("hello world");
list<char> lt4(s.begin(),s.end()); //构造string对象某段区间的复制品

五: 构造数组某段区间的复制品。

int arr[] = {
    1, 2, 3, 4, 5 };
int sz = sizeof(arr) / sizeof(int);
list<int> lt5(arr, arr + sz); //构造数组某段区间的复制品

list的插入和删除

push_front和pop_front

push_front函数用于头插一个数据,pop_front函数用于头删一个数据。

#include <iostream>
#include <list>
using namespace std;

int main()
{
   
	list<int> lt;
	lt.push_front(0);
	lt.push_front(1);
	lt.push_front(2);
	for (auto e : lt)
	{
   
		cout << e << " ";
	}
	cout << endl; //2 1 0
	lt.pop_front();
	for (auto e : lt)
	{
   
		cout << e << " ";
	}
	cout << endl; //1 0
	return 0;
}

push_back和pop_back

push_back函数用于尾插一个数据,pop_back函数用于尾删一个数据。

#include <iostream>
#include <list>
using namespace std;

int main()
{
   
	list<int> lt;
	lt.push_back(0);
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	for (auto e : lt)
	{
   
		cout << e << " ";
	}
	cout << endl; //0 1 2 3
	lt.pop_back();
	lt.pop_back();
	for (auto e : lt)
	{
   
		cout << e << " ";
	}
	cout << endl;//0 1
	return 0;
}

insert

list当中的insert函数支持三种插入方式:

1.在指定迭代器位置插入一个数。
2.在指定迭代器位置插入n个值为val的数。
3.在指定迭代器位置插入一段迭代器区间(左闭右开)。

#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
using namespace std;

int main()
{
   
	list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	list<int>::iterator pos = find(lt.begin(), lt.end(), 2);
	lt.insert(pos, 9); //在2的位置插入9
	for (auto e : lt)
	{
   
		cout << e << " ";
	}
	cout << endl; //1 9 2 3
	pos = find(lt.begin(), lt.end(), 3);
	lt.insert(pos, 2, 8); //在3的位置插入2个8
	for (auto e : lt)
	{
   
		cout << e << " ";
	}
	cout << endl; //1 9 2 8 8 3
	vector
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sherry的成长之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值