I am not able to understand why I am getting an output of 200 whereas by making my own compare function I have reversed the conditions and output should be 100.
#include <iostream>
#include <algorithm>
using namespace std;
bool compare(int a,int b){
return a<=b;
}
int main(){
int arr[]={1,2,5,10,20,50,100,200,500,2000};
int key=120;
int n=sizeof(arr)/sizeof(int);
int lb=lower_bound(arr,arr+n,key,compare)-arr;
int x=arr[lb];
cout<<x<<endl;
return 0;
}
That's not what your
compare
does. You have just changed the comparison, but in a way that still makes200
be the first element for whichcompare
returnsfalse
.If you want to get
100
, you can usestd::prev
to get the previous element pointed at bylower_bound
:and now
*it
will be100
.If you want the index of this element, you can use
std::distance
like this:Here's a demo.
Note that you should account for the fact that
lower_bound
may return an iterator to the beginning of the range, in which case, you can't dostd::prev
on it.