Reputation: 33
I am using custom comparators to priority_queue
, finding different behaviors. I already knew that stl containers need specific type passing to template declaration.
When using normal functions, it should be:
bool cmp(pair<int, int> &lhs, pair<int, int> &rhs) {
return lhs.first > rhs.first;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq1(v.begin(), v.end(), cmp);
But when using lambda, I find the correct way is:
auto comp = [](const pair<int, int>& lhs, const pair<int, int>& rhs){return lhs.second < rhs.second;};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq2(v.begin(), v.end(), comp);
I referred to decltype but did not come out an opinion. Could someone explain how compiler treats decltype(&function)
and decltype(lambda)
?
Upvotes: 1
Views: 55
Reputation: 409136
That's because lambda expressions create an object (of an anonymous class).
If you use &comp
then you get a pointer to the object, which is not callable.
The lambda you have is basically equivalent to
struct
{
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs)
{
return lhs.second < rhs.second;
}
} comp;
Upvotes: 2