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

问题描述

#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(如在 lst compare 100

解决方法

对,正如亚达夫所说。您还可以查看关于比较要求的 cppreference:

comp - 二元谓词,如果第一个参数小于(即排在前面)第二个参数,则返回 true。

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