針對已排序區間 [first, last) 的三大查找算法,均為對數級時間。
bool binary_search(It first, It last, const T& val);
val 是否存在;It lower_bound(It first, It last, const T& val);
< val,返回 last;It upper_bound(It first, It last, const T& val);
≤ val,返回 last;lower_bound == upper_bound ⇔ val 不在區間中;[lower_bound, upper_bound) 即為等於 val 的元素範圍(等價於 equal_range);operator< 或自定義比較器)。vectorpets = {"cat","dog","fish","snake","turtle"}; auto lb = lower_bound(pets.begin(), pets.end(), "dog"); // 指向 "dog" auto ub = upper_bound(pets.begin(), pets.end(), "dog"); // 指向 "fish" cout << *lb << " " << *ub; // 輸出: dog fish