一.list的底层结构
- 带头结点的双向循环链表
二.功能应用
- 1 构造函数
//构造函数
list<int> l1; //空
list<int> l2(10, 5); //放置10个5
vector<int> v1{ 1,2,3,4,5 };
list<int> l3(v1.begin(), v1.end());//范围构造
//拷贝构造函数
list<int> l4(l2);
- 2容量 链表没有容量,也无需修改容量
cout << l1.size()<<" " ;
cout << l1.empty() << endl;
- 3元素访问
//元素访问
cout << l3.front() << " ";//首元素
cout << l3.back() << endl;//尾元素
- 4迭代器
auto it = l2.begin();
while (it != l2.end()) {
cout << *it << " ";
it++;
}
cout << endl;
关于迭代器失效问题以及解决方法
- 元素删除导致迭代器失效
list<int> l{ 0,1,2,3,4,5 };
auto it = l.begin();
l.erase(it);
//野指针,代码奔溃
//解决方法:重新赋值
it = l.begin();
while (it != l.end()) {
cout << *it << " ";
it++;
}
cout << endl;
- 5.元素修改操作
//头插 头删 尾插 尾删
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_front(0);
l.pop_front();
l.pop_back();
- 任意位置插入操作 insert
- 任意位置删除操作 erase
//任意位置插入 删除
//1.库函数find() 得到迭代器it
auto it1 = find(l.begin(), l.end(), 2);
if(it1!=l.end())
//2.插入
l.insert(it1, 5);
//1.库函数find() 得到迭代器it
auto it2 = find(l.begin(), l.end(), 5);
//2.删除
l.erase(it2);
- swap 交换两个链表
list<int> first{ 1,2,3,4,5 };
list<int> second{ 5,4,3,2,1 };
first.swap(second);
- clear 清空链表
first.clear();
- 6list特殊操作
- remove 删除全部值为value的元素
- remove_if 删除所有满足条件的元素
list<int> l{ 1,2,2,3,4,2 };
for (auto e : l)
cout << e << " ";
cout << endl;
//特殊操作
//remove 删除全部值为value的元素
l.remove(2);
//remove_if 删除所有满足条件的元素
l.remove_if(Isodd); //Isodd为函数名
bool Isodd(int data) {
if (data % 2 == 0)
return 1;
return 0;
}
- sort函数 链表从小到大排序
- unique 保证元素唯一,但前提,链表必须有序
list<int> l{3,4,5,6,7,8,5,1,2,1,2,2,3,3,3,4};
//sort 链表从小到大排序
l.sort();
//unique 保证元素唯一,但前提,链表必须有序
l.unique();