【问题标题】:custom comparator in lower_bound() stl function in c++C++ 中的 lower_bound() stl 函数中的自定义比较器
【发布时间】:2021-07-12 11:56:09
【问题描述】:
#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

【问题讨论】:

  • 请以文字而非图片的形式发布代码。您的比较器返回小于或等于,std::lower_bound 预计小于
  • 作为这里的新用户,也请收下tour并阅读How to Ask
  • 您好,欢迎您!请不要分享您的代码图片,而是复制问题中的代码(这就是人们首先投票结束您的问题的原因)。这次我为你做了,向你展示如何做到这一点。作为记录,我从i.stack.imgur.com/m1M04.png复制了你的代码

标签: c++ algorithm sorting data-structures stl


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多