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)
?
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;
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.