Search code examples
c++stlcomparatorpriority-queue

Priority queue lambda comparator and normal comparator


#include <iostream>
#include <queue>
#include <vector>
#include <array>
using namespace std;

auto cmp2(const array<int, 2>& a, const array<int, 2>& b) {
    return a[0]+a[1] > b[0]+b[1];
}

int main() {
    auto cmp = [] (const array<int, 2>& a, const array<int, 2>& b) {
        return a[0]+a[1] > b[0]+b[1];
    };

    priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(cmp)> pq(cmp);

    priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(cmp2)> pq2(cmp2);
}

There is a lambda comparator in the main function and another comparator outside. Why only the first priority queue can compile while the second one cannot and gives an error of invalidly declared function type. Thank you in advance.


Solution

  • cmp is a lambda. It's an object with a () operator.

    But cmp2() is a function.

    You can't use a function as a callable type, but you can use a function pointer as a callable type, in that case you must use decltype(&cmp) to get a function pointer type:

        priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(&cmp2)> pq2(&cmp2);