Doubt in comparator/compare function

When we use bool fn,
We are writing return a<=b;
So basically we are making the lower_bound be like give the number equal to n or smaller to n.
But it will not be correct if suppose i have a set like
a[ ] ={1,2,5,10,20,50,100,200,2000}
We call comparator in lowerbound
auto it=lower_bound{a,a+n,key,compare)-1;
when key=100 *it should be 50
Why is it 100.
Kindly explain

hi @shivamm2110,
As we have changed our comparator function so that it works like upper bound. So it will always return index of that element whose value is greater than the needed value and to get the required value , we need to do -1.
Suppose, If we dont use comparator, then the lower bound function gives the first value in the sorted array that is greater than or equal to the value to be found i.e it will ignore all values smaller than the value to be found. But, when we define a comparator same as defined in the lecture, the lower bound function ignores all the value smaller than or equal to the value to be found and hence will always return the index of key which has value greater than the value to be found. Hence we will have to subtract 1 from index in order to get the index of key which has value smaller than or equal to the required value.
By using a<=b, comparator function returns true for all elements <= value to be found. When the comparator function returns false at that time we see that the current index might be the answer. If we dont use comparator function, it returns true only for elements < value to be found.

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.