Lower_bound function

In the lower_bound function with the comparator added in the argument, why do we need to subtract 1 now when calculating the value of lb? Since the compare function will do the needful then why we need to subtract 1

Hello @shantanusharma,

The comparator returns the address of 100 only.
But when you subtract coins i.e. the address of first element of the array, it gives the position of 100 in the array i.e. 7.
But, you access the elements with the index at which they are present.
Also, the index begins with 0.
So, the relationship between index and position of an element in an array is, index=position-1
This to get the index of 100 we are then subtracting 1 from the position obtained i.e. 7-1=6.
So, arr[6] is 100, not 200.

for money=100, lower_bound(coins,coins+n,money,compare) function will give 7 as output because it is present at 7th position.
so finally, lb=7-0-1=6 coins [6]=100.
Suggestion:
Try to print lower_bound(coins,coins+n,100,compare)-coins.

Hope, this would help.

1 Like

Thanks for the help.