![]() |
VOOZH | about |
std::lower_bound is a Standard Template Library (STL) algorithm used to find the first position where a given value can be inserted in a sorted range without violating the order. In simple terms, it returns an iterator pointing to the first element that is greater than or equal to (>=) the given value.
Example 1: Find Lower Bound in a Vector
30
Explanation:
iterator lower_bound(iterator first, iterator last, const T& value);
Note: If the range is not sorted or at least partitioned with respect to the given value, the behaviour of this function is undefined.
The below examples demonstrate some of its common uses.
Example 1: Find the Lower Bound of a Value in Array
40
Explanation: lower_bound() finds and prints the first element in the sorted array that is greater than or equal to 35, which is 40.
Example 2: Find lower_bound() in a Vector of String Using 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: Find the Existence of an Element in Vector
40 is found.
Explanation: The lower_bound() function will return the iterator to the given value if it is present in the vector. If it is not present, it will return iterator to the largest element smaller than the given value.
Example 4: Find the Number of Smaller and Larger Elements than a Value in Vector
No. of Smaller Elements: 3 No. of Larger Elements: 2
Explanation: lower_bound() finds the position where 35 would be inserted in the sorted vector; elements before it are smaller, and the remaining elements are larger.
Example 5: Insert an Element in a Sorted Vector
10 20 30 35 40 50
Explanation: The lower_bound() returns the position by which the vector is partitioned with respect to the given value. In other words, if the element was present in the sorted vector, it would be present at this position.
Example 6: Finding the Lower Bound in a Set
40
Explanation: This code finds and prints the first element in the set that is greater than or equal to 35, which is 40 (though using set::lower_bound() is recommended for better performance).