lower_bound() 中的自定义比较器 c++ 中的 stl 函数

custom comparator in lower_bound() stl function in c++

#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a,int b){
    cout<<a<<" "<<b<<endl;
    return a<=b;
}

int main()
{    int n;
    cin>>n;
    int a[n]={1,2,5,10,50,100,200,500,2000};
    int money=100;
    int it =lower_bound(a,a+n,money,compare)-a;
    cout<<a[it];
    return 0;
}

在这段代码中,我为lower_bound()做了一个自定义的比较器,所以它应该最后输出100(因为在第一个比较中100 <=100是真的)。但它给出了下一个索引 (200) 作为输出...为什么?

对,正如亚达夫所说。您还可以查看 cppreference about compare requirement:

comp - 如果第一个参数小于(即先于)第二个参数,则 returns 为真。

https://en.cppreference.com/w/cpp/algorithm/lower_bound