Can't understand lower bound function with comparator

190 views Asked by At

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;
}
1

There are 1 answers

2
cigien On

whereas by making my own compare function I have reversed the conditions

That's not what your compare does. You have just changed the comparison, but in a way that still makes 200 be the first element for which compare returns false.

If you want to get 100, you can use std::prev to get the previous element pointed at by lower_bound:

auto it = std::prev(lower_bound(std::begin(arr),std::end(arr),key), 1);

and now *it will be 100.

If you want the index of this element, you can use std::distance like this:

int index = std::distance(std::begin(arr), it);

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 do std::prev on it.