| 特性 | std::find | std::binary_search |
|---|---|---|
| 前提條件 | 無序/有序皆可 | 範圍必須已按相同準則排序 |
| 時間複雜度 | O(N) 線性掃描 | O(log N) 二分查找 |
| 返回值 | 迭代器 (找到指向元素,否則 end()) | bool (僅判斷是否存在) |
| 適用迭代器 | InputIterator (單向) | ForwardIterator (需隨機訪問更佳) |
| 自定義比較 | 支援一元謂詞 (C++11 find_if) | 支援二元比較函數 |
C++ 標準庫關聯容器 (`std::set`, `std::map`, `std::multiset`...) 內部默認升序 (用 `std::less`)。可自定義比較函數實現降序或其他嚴格弱序。`std::vector` 等序列容器需手動 `std::sort` 並保持有序。
std::lower_bound / upper_bound / equal_range:返回插入位置/區間,比 `binary_search` 資訊更豐富。std::find_if / find_if_not:條件查找。std::search / search_n:子序列查找。std::adjacent_find:相鄰重複元素。find。binary_search / lower_bound / 關聯容器 (`set`/`map`)。