重载lower_bound函数

对结构体数组用lower_bound函数

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int x,y;
    node(int x=0,int y=0)
    {
        this->x=x;
        this->y=y;
    }
    friend bool operator<(const node&a,const node&b)
    {
        if(a.x==b.x)
            return a.y<b.y;
        return a.x<b.x;
    }
}per[5];


int main()
{
    per[0]=node(0,3);
    per[1]=node(0,2);
    per[2]=node(0,7);
    per[3]=node(6,1);
    per[4]=node(4,5);
    sort(per,per+5);
    for(int i=0;i<5;i++) cout<<per[i].x<<"  "<<per[i].y<<"      ";
    cout<<endl;
    int pos=lower_bound(per,per+5,node(6,0))-per;
    cout<<pos<<endl;
    return 0;
}

对int  a[maxn] 用lower_bound,只能在a数组是上升序列的时候,查找第一个大于等于x的数

但是如果加了cmp函数重载lower_bound函数的'<'大于号

bool cmp(const int &a,const int&b)
{
    return a>b;
}

 重载为'>'小于号,那么lower_bound(a+1,a+n+1,x,cmp) 就是查找第一个小于等于x的数,upper_bound则是查找第一个小于x的数

原文地址:https://www.cnblogs.com/eason9906/p/11754780.html