| 迭代器類別 | 算法 | 複雜度 |
| ForwardIterator | 交換兩段,再內部循環交換 | O(n),較多交換 |
| BidirectionalIterator | 三次 reverse:reverse(first,mid), reverse(mid,last), reverse(first,last) | O(n),優雅 |
| RandomAccessIterator | GCD 循環置換:分 gcd(n, k) 個環,每環循環移動 | O(n),最少賦值 |
partition / stable_partition:分區
// 關鍵常數
const int __stl_threshold = 16;
// introsort_loop
while (last - first > __stl_threshold) {
if (depth_limit == 0) { partial_sort(first, last, last); return; }
--depth_limit;
cut = unguarded_partition(first, last, median3);
introsort_loop(cut, last, depth_limit);
last = cut; // 尾遞歸優化
}
final_insertion_sort(first, last);
nth_element:選擇算法
快速選擇:partition 後只遞歸包含第 n 個元素的那一側,平均 O(n)。
lower_bound / upper_bound / equal_range:二分查找
| 算法 | 條件 | 返回 |
| lower_bound | `*mid < val` 向右 | 首個 ≥ val |
| upper_bound | `val < *mid` 向左 | 首個 > val |
| equal_range | 先找任一 == val,再分別調用 lower/upper | [lower, upper) |
merge / set_operations:有序區間運算
// 1. 從右向左找首個 a[i] < a[i+1]
// 2. 從右向左找首個 a[j] > a[i]
// 3. swap(a[i], a[j])
// 4. reverse(a[i+1], end)
// 字典序下一排列,O(n)
heap 操作:make_heap, push_heap, pop_heap, sort_heap
- 底層:完全二叉樹數組表示
- 調整:`__adjust_heap`、`__push_heap`、`__pop_heap`
- sort_heap:反覆 pop_heap 獲得有序序列
核心設計智慧
- 迭代器分類:針對不同能力提供最優算法
- 尾遞歸優化:`introsort_loop` 消除一半遞歸
- 三數取中樞紐:避免有序數組最壞情況
- 混合策略:大數據快排、深度過大堆排、小數據插排
- 未檢查版本:`unguarded_*` 省去邊界檢查,性能極致
研讀 STL 源碼不僅能理解算法細節,更能學習到泛型編程、性能優化、接口設計的精髓。
- 上一篇文章: HDU 4772 Zhuge Liang's Password:矩陣旋轉最大匹配數
- 下一篇文章: NYUOJ 8 多關鍵字排序去重:結構體排序與輸出
Copyright ©
程式碼之家 All Rights Reserved