![]() |
VOOZH | about |
upper_bound is a Standard Template Library (STL) function used to find the first element that is strictly greater than a given value in a sorted range. It is commonly used for efficient searching and range queries in sorted containers.
Example: Basic Usage with Vector
40
Explanation:
iterator upper_bound(iterator first, iterator last, const T& value);
Note: The behavior of std::upper_bound() is undefined if the range is not sorted
The below examples demonstrate some of its common uses.
Example 1: Find Upper Bound in an Array
40
Explanation: This code uses upper_bound() to find and print the first element in the sorted array that is strictly greater than 30, which is 40.
Example 2: Use upper_bound() with Custom Comparator
banana
Explanation: We need to use the custom comparator function to perform the case insensitive search as the default comparator treats the uppercase and lowercase differently.
Example 3: Check for an Element in a Sorted Vector
40 is found.
Explanation: upper_bound() returns the iterator just after the matching value; to check if the value exists, decrement the iterator and compare.
Example 4: Count Elements Smaller and Larger than a Value
No. of Smaller Elements: 3 No. of Larger Elements: 2
Explanation: Counts elements based on the position returned by upper_bound().
It is recommended to use set::upper_bound() for set as sets do not have random access to its elements. So, the upper_bound() function have to increment it sequentially to find the middle element (part of binary search algorithm) each time leading to increased time complexity.
set::upper_bound -> 6 std::upper_bound -> 6
Explanation: