1. 程式人生 > >upper_bound()比較函式的自定義方法

upper_bound()比較函式的自定義方法

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int l[3]={0,10,20};
vector<int>ar;
struct cmp_lower	//lower_bound
{
    bool operator  () (int index,int x)
    {
        return l[index]<x;
    }
};
struct cmp_upper		//upper_bound
{
    bool operator  () (int x,int index)
    {
        return x<l[index];
    }
};
 
int main ()
{
    for(int i=0;i<3;i++)
        ar.push_back(i);
    int x;
    while(cin>>x)
    {
        int lower_result=lower_bound(ar.begin(),ar.end(),x+1,cmp_lower())-ar.begin();
        int upper_result=upper_bound(ar.begin(),ar.end(),x,cmp_upper())-ar.begin();
        printf("lower_result:%d  upper_result:%d\n",lower_result,upper_result);
    }
    return 0;
}

用c++11的lambda

upper_bound(ar.begin(),ar.end(),x,
[&](int const x, // this x is the previous x
    int const index /* this value will come from vector ar*/)
{
 return a[index] < x;
});