Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda for compare function in c++ not working

Tags:

c++

lambda

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
like image 248
F777 Avatar asked May 07 '26 03:05

F777


1 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
like image 170
songyuanyao Avatar answered May 09 '26 02:05

songyuanyao