mardi 20 février 2018

What is the difference when passing function's reference and lambda expression as arguments?

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

Aucun commentaire:

Enregistrer un commentaire