Lambda for compare function in c++ not working

Viewed 80

This code produces an error:

priority_queue<int, vector<int>, [](int a, int b)->bool{return a>b;}> q;

Why? (I know that for things like this I can just use std::greater or the default sorting, but I'm trying to learn how to create a custom comparator)

2 errors generated:

error: no matching function for call to object of type lambda
error: template argument for template type parameter must be a type
2 Answers

You need to specify the type, but not the lambda expression itself as the template argument. And lambda should be specified as constructor argument.

E.g.

auto c = [](int a, int b)->bool{return a>b;}; // declare lambda in advance
priority_queue<int, vector<int>, decltype(c)> q(c);
//                               ^^^^^^^^^^^      <- specify the type of lambda
//                                              ^ <- specify the lambda as constructor argument

You can use std::function instead of lambda

auto q = std::priority_queue<int, std::vector<int>, std::function<bool(const int&, const int&)>>{
            [](const int& a, const int& b)
            {
                return a < b;
            }
    };
Related