C++20 sections · 1024 units
Open in Course

binary_search

Find insertion point

I'll show you binary_search(v.begin(), v.end(), target) to check if a value exists in O(logn)O(\log n) time. It returns a boolean indicating whether the target was found. You must sort the range first: sort(v.begin(), v.end()) before calling binary_search().

If the vector isn't sorted, results are undefined and likely incorrect. This function only tells you whether the value exists, not where it is. Use lower_bound() instead if you need the position or an iterator to the found element.