C++ Snippet

std::lower_bound Recipes

Difficulty: Medium

`std::lower_bound` returns an iterator to the first element NOT less than a target in a sorted range, while `std::upper_bound` returns the first element strictly greater. This snippet shows how to use both for sorted-insertion, range-counting, and predicate-based binary search via the comparator overload. All run in O(log n) on random-access iterators.

Code Snippets
/

std::lower_bound Recipes

std::lower_bound Recipes

`std::lower_bound` returns an iterator to the first element NOT less than a target in a sorted range, while `std::upper_bound` returns the first element strictly greater. This snippet shows how to use both for sorted-insertion, range-counting, and predicate-based binary search via the comparator overload. All run in O(log n) on random-access iterators.

C++
Medium
3 snippets
cpp-algorithms-stl
binary-search
binary-search-templates

492 views

14

Both functions assume the input range is already sorted (or at least partitioned by the predicate); the result on an unsorted range is unspecified. The half-open interval [lower_bound, upper_bound) is exactly the run of elements equal to the target, so upper - lower gives the count of duplicates in O(log n). For a contains-check, compare *lower_bound with the target after verifying the iterator is not at end(). std::binary_search exists for this case but only returns a bool; lower_bound is more useful because you keep the iterator for further work.