lower_bound in C++
The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns the index of the next smallest number just greater than or equal to that number. If there are multiple values that are equal to val, lower_bound() returns the index of the first such value.
The elements in the range shall already be sorted or at least partitioned with respect to val.
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
Parameters: The above methods accept the following parameters.
- first, last: The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
- val: Value of the lower bound to be searched for in the range.
- comp: Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, and the second, always val), and returns a value convertible to bool. The function shall not modify any of its arguments. This can either be a function pointer or a function object.
Return Value: An iterator to the lower bound of val in the range. If all the elements in the range compare less than val, the function returns last. If all the elements in the range are larger than val, the function returns a pointer to the first element.
Input: 10 20 30 40 50 Output: lower_bound for element 30 at index 2 Input: 10 20 30 40 50 Output: lower_bound for element 35 at index 3 Input: 10 20 30 40 50 Output: lower_bound for element 55 at index 5 Input: 10 20 30 30 30 40 50 Output: lower_bound for element 30 at index 2
Vector contains : 10 20 30 30 30 40 50 lower_bound for element 30 at position : 2 lower_bound for element 35 at position : 5 lower_bound for element 55 at position : 7
Time Complexity: The number of comparisons performed is logarithmic. Therefore, the time complexity of the above approach is O(logN), where N = size. (last – first)
This article is contributed by Sachin Bisht, . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.