list 链表容器是对双向链表的泛化实现,通过指针将不同的存储位置的元素链接构成线性序列。
#include<list> 头文件必须包含
list的成员函数:
- push_back() 尾部插入
- push_front() 头部插入
- empty() 判断是否为空
- resize(n) 重新指定长度,超出的部分元素将被删除
- pop_back() 尾部删除
- pop_front() 头部删除
- assign(n,elem) 用n 个elem 替换调用本函数的list对象
- swap() 用于交换两个链表
- reverse()将链表元素逆置
- insert()在链表中插入元素
- erase() 删除元素
- remove() 从链表中移除元素
#include<iostream>
#include<list>//引入头文件
#include<string>
using namespace std;
int main()
{
list<int> v;//创建一个空链表
v.push_back(1);//链表尾部插入1
v.push_front(0);//链表头部插入0
if (!v.empty())
{
for (auto a : v)
{
cout << a;
}
cout << endl;
}
v.resize(10);//重新分配空间
for (auto a : v)
{
cout << a;
}
cout << endl;
v.clear();//清空链表
for (auto a : v)
{
cout << a;
}
cout << endl;
list<int>v2 = { 1,2,3,4,5,6 };
cout << v2.front() << endl;//返回链表第一个元素
cout << v2.back() << endl;//返回链表最后一个元素
v2.pop_back();//删除最后一个元素
v2.pop_front();//删除第一个元素
for (auto a : v2)
{
cout << a;
}
cout << endl;
//v2.assign(2, 0);//将v2中的(所有)元素替换2个0
//for (auto a : v2)
//{
// cout << a;
//}
v2.swap(v);//交换list内的元素
for (auto a : v2)
{
cout << a;
}
list<string>v3 = {"a","b","c","d"};
v3.reverse();//逆置元素
for (auto a : v3)
{
cout << a;
}
return 0;
}