#include
#include
using namespace std;
bool compare(int a,int b){
return a<=b;
}
int main() {
int coins[]={1,2,5,10,20,50,100,200,500,2000};
int n=sizeof(coins)/sizeof(int);
int money =168;
int lb=lower_bound(coins,coins+n,money,compare)-coins-1;
cout<<lb;
return 0;
}
Why we are subtracting 1 in the line lb=lower_bound…-coins-1; since according to lower_bound def and we are using comparator too it should return 100 without using -1 but it is returning 200 without using -1.
Doubt in lower_bound defnition
@Ramitcodingblocks actual comaarator function for lower_bound return a<b but we have used here equality too (a<=b) hence if you don’t use -1 lower bound for 100 will return 200.
sir lower_bound fxn returns 1st bucket which is >=key but here as we used comparator with a<=b then also it should return 100 why to use extra -1 for it.
@sdevwrat sir lower_bound fxn returns 1st bucket which is >=key but here as we used comparator with a<=b then also it should return 100 why to use extra -1 for it.
sir not getting please explain.
If u observe that
if u just write
lower_bound(arr,arr+n,key,compare)
without -1 then giving a money value which exists in the array
would return a wrong value
it returns the next greater value in the array
hence the -1 is required so that even 120 and 100 would give us answer 100
in case -1 is not written then 100 would give answer 200 because of the comparator.