一.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();