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的成员函数的使用,我觉得还是挺清楚明白的! 唐怡佳继续加油叭!