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
comparedoes. You have just changed the comparison, but in a way that still makes200be the first element for whichcomparereturnsfalse.If you want to get
100, you can usestd::prevto get the previous element pointed at bylower_bound:and now
*itwill be100.If you want the index of this element, you can use
std::distancelike this:Here's a demo.
Note that you should account for the fact that
lower_boundmay return an iterator to the beginning of the range, in which case, you can't dostd::prevon it.