C++20 sections · 1024 units
Open in Course

upper_bound

Beyond the value

I'll show you upper_bound(v.begin(), v.end(), x) to find the first element strictly greater than x. It returns an iterator to that element or v.end() if none exists. You can count occurrences in a sorted vector by subtracting bounds: upper_bound(v.begin(), v.end(), x) - lower_bound(v.begin(), v.end(), x) gives the frequency of x.

The difference between upper and lower bounds identifies all elements equal to x. Both functions require sorted ranges and run in O(logn)O(\log n) time using binary search.