C++20 sections · 1024 units
Open in Course

lower_bound

Finding insertion points

I'll show you lower_bound(v.begin(), v.end(), x) to find the first element not less than x. It returns an iterator pointing to that element or v.end() if none exists. You'll use this to find where x would be inserted while keeping the vector sorted.

The range must already be sorted in ascending order for this to work correctly. Get the index by subtracting iterators: lower_bound(v.begin(), v.end(), x) - v.begin() gives you the position.

Time complexity is O(logn)O(\log n) using binary search.