The lower_bound()
function is used to find the first element in the range [start, end)
whose value is less than val
, and returns an iterator pointing to the next smallest number that is either greater than or equal to the val
.
This function accepts the following parameters:
start
: This parameter specifies the start index of the array or vector where you want to search.end
: This parameter specifies the end index of the array or vector where you want to search.value
: This is the value that you want to search for.comp
: This is an optional parameter that is used to compare the values in the array. It can be used if we want to compare the values in a custom way.The lower_bound()
function returns an iterator that points to the first value that is just greater than or equal to the specified value
.
Let’s look at the code now:
#include <iostream>#include <algorithm>using namespace std;int main() {vector<int> vec = {10,20,30,10,40,20,40,20,10,40,30};auto it = lower_bound(vec.begin(), vec.end(), 20);cout << "The index is " << (it - vec.begin());return 0;}
Explanation:
On lines 1 and 2, we import the required package.
In line 6, we define the vector with some integer elements.
In line 7, we call the function lower_bound
and pass the parameters. We want to search for 20 in the vector.
In line 8, we print the index of the element that is just greater than or equal to 20. Remember that we get an iterator from the lower_bound()
function, so to get the index, we need to subtract it from the vec.begin()
iterator.
We can see that it returns the index 1, which means the element at index 1 is the first element that is just greater than or equal to the specified value, i.e., 20.
Now, let’s look at another example, in which we will find the index of the first occurrence of the specified element in the array. For this, we first need to sort the array. Let’s look at the code now:
#include <iostream>#include <algorithm>using namespace std;int main() {vector<int> vec = {10,20,30,10,40,20,40,20,10,40,30};sort(vec.begin(), vec.end());// vec becomes {10,10,10,20,20,20,30,30,40,40,40};auto it = lower_bound(vec.begin(), vec.end(), 20);cout << "The index is " << (it - vec.begin());return 0;}
Explanation:
In lines 1 and 2, we import the required package.
In line 7, we sort the vector using the in-built sort()
function.
In line 9, we call the function lower_bound()
and pass the required parameters.
In line 10, we print the index of the first occurrence of the element i.e. 20.
We can see that in this case, we get the index as 3.
In this way, we can use the lower_bound()
functions in many coding problems to reduce the effort of finding the index of an element in an array.