65,186
社区成员




#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 l[index]<x;
}
};
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;
}
struct comp_t
{
int const* const l;
comp_t (int const* const local_l) : l(local_l) { }
bool operator () (int const x, int const index) const
{
return l[index] < x;
}
} const comp(l); // capture the l array.
upper_bound(ar.begin(),ar.end(),x,comp);
实际上 lambda 只不过是编译器帮你做上面手写的这些事儿,所以 lambda 能做到的,不用 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 l[index] < x;
});