#include
#include
using namespace std;
int main()
{
int arr[5] = { 4, 5, 1, 0, 1 };
sort( arr, arr+5 );
cout<< lower_bound( arr, arr+5, 3 ) - arr <<endl;
return 0;
}
//here what the lower_bound function doing?please explain the whole cout statement
Quiz-1 of STL: question NO:5
@hrit04 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.
After sorting, array becomes 0 1 1 4 5
So it gives us an iterator(or pointer) to 4, index is 3.
If we do cout << pointer (like cout << lower_bound(arr, arr+5. 3)
), it gives us address
of that element, not the value.
if we do cout << *pointer (like cout << *lower_bound(arr,arr+5,3)) it will give us the value at that address, ie
4`
Now arr, stores the base address, ie address of the first element. By subtracting the base address from the returned address, we actually get the index of that element.
for eg let the base address be 2000
so assuming int takes up 4 bytes
0 : 2000
1 : 2004
2 : 2008
3 : 2012
4 : 2016
so the subtraction operation actually does, (2012 - 2000)/4 basically, (add1-add2)/size of datatype and the answer comes out to be 3
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.