🔥 特点:list
任何位置执行插入和删除动作都非常快
list 每个节点包含数据域和指针域,不支持随机存取
list 链式存储,遍历速度没有数组 vector 快
STL 中的链表是一个双向循环链表
步骤零: 使用时需要包含头文件 #include <list>
void printList(list<int> &l) // 逐个元素打印
{
for (list<int>::iterator i = l.begin(); i!=l.end(); i++)
{
cout << *i << endl;
}
}
💜 list 构造与赋值
// 1. 默认构造
list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
list<int> l11;
l11 = l1; // 赋值 0 1 2 3 4 5 6 7 8 9
l11.assign(l1.begin(), l1.end()); // 赋值 0 1 2 3 4 5 6 7 8 9
l11.assign(10, 1); // 赋值 1 1 1 1 1 1 1 1 1 1
// 2. 通过区间构造
list<int> l2(l1.begin(), l1.end());
// 3. n个element
list<int> l3(10, 1);
// 4. 拷贝构造
list<int> l4(l1);
💜 list 插入和删除:push_back/front
、pop_back/front
、insert
、erase
、clear
、remove
list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
l1.push_back(10); // 0 1 2 3 4 5 6 7 8 9 10 - 尾插 10
l1.pop_back(); // 0 1 2 3 4 5 6 7 8 9 - 尾删 10
l1.push_front(-1); // -1 0 1 2 3 4 5 6 7 8 9 - 头插 -1
l1.pop_front(); // 0 1 2 3 4 5 6 7 8 9 - 头删 -1
l1.insert(l1.begin(), -1); // -1 0 1 2 3 4 5 6 7 8 9 - l1.begin() 处插入 -1
l1.erase(l1.begin()); // 0 1 2 3 4 5 6 7 8 9 - l1.begin() 处删除 -1
l1.clear(); // 清空
list<int> l2 = {0,1,2,3,4,4,4,5,6,7,8,9};
l2.remove(4); // 0 1 2 3 5 6 7 8 9 - 移除 4 (所有)
💜 list 大小获取:empty
、 size
list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
cout << l1.empty() << endl; // 0
cout << l1.size() << endl; // 10
💜 list 元素互换:swap
list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
list<int> l2 = {-0,-1,-2,-3,-4,-5,-6,-7,-8,-9};
l1.swap(l2);
// l1: -0,-1,-2,-3,-4,-5,-6,-7,-8,-9
// l2: 0,1,2,3,4,5,6,7,8,9
💜 list 反转和排序:reverse
、sort
// 需要头文件 #include <algorithm>
list <int>l1 = {0,1,3,2,4,8,5,6,7,9};
l1.reverse(); // 9 7 6 5 4 2 3 1 0
l1.sort(); // 0 1 2 3 4 5 6 7 8 9
l1.sort(greater<int>()); // 9 8 7 6 5 4 3 2 1 0