[英]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;
}
In this code, I made a custom comparator for lower_bound()
, so it is supposed to output 100 in the end (as in the lst compare 100 <=100 is true).在这段代码中,我为
lower_bound()
做了一个自定义比较器,所以它应该最终是 output 100 (如在 lst compare 100 <=100 为真)。 But it gives the next index (200) as an output... why?但它给出了下一个索引(200)作为 output ......为什么?
Right, just as Yadav said.没错,正如亚达夫所说。 You can also see cppreference about compare requirement:
您还可以查看有关比较要求的 cppreference:
comp - binary predicate which returns true if the first argument is less than (ie is ordered before) the second. comp - 如果第一个参数小于(即排在前面)第二个参数,则返回 true 的二进制谓词。
https://en.cppreference.com/w/cpp/algorithm/lower_bound https://en.cppreference.com/w/cpp/algorithm/lower_bound
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.