Lets say a have a class A
that can be evaluated to an integer.
We get as input a vector of A
that is sorted by it's evaluate()
value.
How can I find the upper bound by the evaluated value?
I tried this but it doesn't compile.
class A;
int evaluate(const A& a);
// ...
vector<A>::iterator foo(vector<A>& v, int k)
{
return upper_bound(v.begin(), v.end(), k,
[](const A& a, int k)
{
return evaluate(a) < k;
}
);
}
While other users have correctly pointed out the problem (eg "You got the order of the arguments in the lambda wrong" by @StoryTeller), please allow me to put down a piece of code that compiles on my machine, for other viewers' reference.
#include <algorithm>
#include <iostream>
#include <vector>
class A
{
public:
int data;
A(int data) : data(data) {}
};
int evaluate(const A & a)
{
return a.data;
}
std::vector<A>::iterator foo(std::vector<A> & v, int k)
{
return std::upper_bound(v.begin(), v.end(), k,
[](int k, A & a) { return evaluate(a) > k; }); // first argument always val
}
int main()
{
std::vector<A> vec {36, 42, 57};
std::cout << foo(vec, 42) - vec.begin() << std::endl; // 2
}
According to [upper.bound]
in the C++17 standard:
... the following corresponding conditions hold: ... or
comp(value, *j) == false
.
That means you will get calls to comp
(your predicate) with the first argument being the value
you passed; and the second argument the dereferenced iterator.
In other words, you likely want your predicate to have type:
bool (int, const A&)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.