upper_bound()比较函数的定义步骤
upper_bound()比较函数的定义方法我定义了一个vectorintar,ar中存有3个元素:0,1,2。另外还有一个数组l[3]
upper_bound()比较函数的定义方法 我定义了一个vector<int>ar,ar中存有3个元素:0,1,2。另外还有一个数组l[3]={0,10,20}。 若给定一个数x,此时我想要利用upper_bound()函数查找ar中的第一个满足l[a]>x的元素a。 那么函数upper_bound(ar.begin(),ar.end(),x,cmp())中的第四个参数cmp()该怎么定义呢? [解决办法] 用 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; });[解决办法] 引用: Quote: 引用: 要求支持新标准,如果你的编译器不支持,还可以使用下面的方法。 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 也都能做到,只不过是费不费事的问题。引用: 要求支持新标准,如果你的编译器不支持,还可以使用下面的方法。 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 也都能做到,只不过是费不费事的问题。 我对比较函数的写法了解的比较少,若这样写可以吗? struct cmp { bool operator () (int a,int b) { return l[a]<b; } };
这样写,l不在作用域内