forward_list(C++11)實現單向鏈表,<forward_list>。特點:
O(1) 插入/刪除,不支援隨機訪問size() 需遍歷計算(C++11 無,C++20 有)list 節省空間(無前驅指針),適合不需雙向遍歷場景forward_list c; // 空
forward_list c(c2); // 複製
forward_list c = c2; // 複製
forward_list c(move(c2)); // 移動
forward_list c(n); // n個默認值
forward_list c(n, val); // n個val
forward_list c(beg, end); // 範圍
forward_list c = {1,2,3}; // 初始化列表
c.assign({4,5,6}); // 列表賦值
c.assign(n, val); // 重複值賦值
c.assign(beg, end); // 範圍賦值
c1.swap(c2); swap(c1, c2); // 交換
c.front() // 首元素(無邊界檢查)
c.before_begin() // 首前位置迭代器(關鍵:插入/刪除首元素需用它)
c.begin(), c.end()
c.cbefore_begin(), c.cbegin(), c.cend()
關鍵點:單向鏈表無 back()、push_back()、rbegin()。操作首元素前驅需 before_begin()。
c.push_front(val) // 首部插入
c.pop_front() // 首部刪除
c.insert_after(pos, val) // pos後插入,返回新元素迭代器
c.insert_after(pos, n, val) // pos後插入n個
c.insert_after(pos, beg, end) // pos後插入範圍
c.insert_after(pos, init_list) // pos後插入列表
c.emplace_after(pos, args...) // pos後原地構造
c.emplace_front(args...) // 首部原地構造
c.erase_after(pos) // 刪除pos後元素,返回下一個
c.erase_after(beg, end) // 刪除範圍
c.remove(val) // 刪除所有值為val
c.remove_if(pred) // 刪除滿足謂詞
c.resize(n) / c.resize(n, val) // 調整大小
c.clear() // 清空
c.unique() // 刪除相鄰重複(需有序配合sort)
c.unique(pred) // 自定義相等判斷
c.splice_after(pos, c2) // 移動c2所有元素到pos後
c.splice_after(pos, c2, it) // 移動c2中it後元素
c.splice_after(pos, c2, beg, end) // 移動c2範圍元素
c.merge(c2) // 合併兩有序鏈表(c2變空)
c.merge(c2, comp) // 自定義比較
c.sort() / c.sort(comp) // 歸併排序 O(n log n)
c.reverse() // 反轉鏈表
forward_list l1 = {1,2,3,4}, l2 = {77,88,99};
l2.insert_after(l2.before_begin(), 99);
l2.push_front(10);
l2.insert_after(l2.before_begin(), {10,11,12,13});
// l2: 10 11 12 13 10 99 77 88 99
l1.insert_after(l1.before_begin(), l2.begin(), l2.end());
// l1: 10 11 12 13 10 99 77 88 99 1 2 3 4
l2.erase_after(l2.begin()); // 刪除第2個
l2.erase_after(find(l2.begin(),l2.end(),99), l2.end()); // 刪除99後所有
l1.sort(); l2 = l1; l2.unique(); // 排序去重
l1.merge(l2); // 合併有序表
initial: list1: 1 2 3 4 list2: 77 88 99 6 new elems: list1: 1 2 3 4 list2: 10 11 12 13 10 99 77 88 99 list2 into list1: list1: 10 11 12 13 10 99 77 88 99 1 2 3 4 list2: 10 11 12 13 10 99 77 88 99 delete 2nd and after 99: list1: 10 11 12 13 10 99 77 88 99 1 2 3 4 list2: 10 12 13 10 99 sorted and unique: list1: 1 2 3 4 10 10 11 12 13 77 88 99 99 list2: 1 2 3 4 10 11 12 13 77 88 99 merged: list1: 1 1 2 2 3 3 4 4 10 10 10 11 11 12 12 13 13 77 77 88 88 99 99 99 list2: (empty)