【贼好理解!!】C++ list链表常用成员函数讲解

list常用成员函数介绍,今天正好学到这一节,就顺便记录一下! 小唐纯手敲 , 希望对大家有帮助


函数介绍

函数说明
void merge(list<T,Alloc>&x)将调用链表和链表x合并,并且储存在调用链表中,x链表将空,且在合并前需保证调用链表和x均已经排序,函数复杂度为线性时间
void remove(const T & val)删除调用链表中所有val,函数复杂度为线性时间
void sort()将调用链表按升序排列,N个元素的复杂度为NlogN
void splice(iterator pos,list<T,Alloc>x)将链表x的内容插入到pos的前面,x链表将为空,函数复杂度为固定时间
void unique()将调用链表中连续相同的元素压缩为单个元素,函数复杂度为线性时间

代码示例讲解

//TangYiJia 2023.1.25

#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>

void outint(int n) {
	std::cout << n << " ";
}

int main(void) {
	using namespace std;

	list<int> one(5, 2);  //5个2
	int stuff[5] = { 1, 2, 4, 8, 6 };
	list<int> two;
	two.insert(two.begin(), stuff, stuff + 5);
	int more[6] = { 6, 4, 2, 4, 6, 5 };
	list<int> three(two);  //复制构造
	three.insert(three.end(), more, more + 6);

	cout << "list one : ";
	for_each(one.begin(), one.end(), outint);
	cout << endl;
	cout << "list two : ";
	for_each(two.begin(), two.end(), outint);
	cout << endl;
	cout << "list three : ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	three.remove(2);  //把three里面的2全删了,函数复杂度为线性时间
	cout << "After three.remove(2) :";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	three.splice(three.begin(), one); //splice完以后,one里的东西都没了,直接移到three里去了,函数复杂度为固定时间
	cout << "After three.splice(three.begin(), one) : ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	cout << "list one : "; 
	for_each(one.begin(), one.end(), outint);
	cout << endl;
	three.unique();  //把three里的连续相同元素压缩为单个元素,函数复杂度为线性时间
	cout << "After three.unique() : ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	three.sort(); //升序排列 N个元素的复杂度为NlogN
	cout << "After three.sort() : ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	three.unique();
	cout << "After three.unique() : ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	two.sort();
	three.merge(two); //将three和two合并,合并前需俩链表都已排序,合并后保存在three中,two没了
	cout << "After tthree.merge(two) ,list three : ";
	for_each(three.begin(), three.end(), outint);
	cout << endl;
	cout << "After three.merge(two) ,list two : ";
	for_each(two.begin(), two.end(), outint);
	cout << endl;

	return 0;
}

运行结果

在这里插入图片描述

总结

本文仅仅简单介绍了list的成员函数的使用,我觉得还是挺清楚明白的! 唐怡佳继续加油叭!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小唐YiJiaTang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值