Reputation: 353
You can define priority queue with lambda as
auto cmp = [] (const MyClass& a, const MyClass& b) -> bool{return a.v2 > b.v2};
priority_queue<MyClass, std::vector<MyClass>, decltype(cmp)> pq(cms);
When I use function object(custom comparison) to define map of priority queue, there is no error.
unordered_map<int, priority_queue<int, std::vector<int>, greater<int>> my_map;
But when I use same technique(custom comparison using lambda) to define map of priority queue I get error.
unordered_map<MyKeyClass, priority_queue<MyClass, std::vector<MyClass>, decltype(cmp)>> my_map;
Error
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/queue:447:16: error: no matching constructor for initialization of 'std::__1::priority_queue<int, std::__1::vector<int, std::__1::allocator<int>
>, (lambda at avg5.cpp:13:24)>::value_compare' (aka '(lambda at avg5.cpp:13:24)')
: c(), comp() {}
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/tuple:1401:7: note: in instantiation of member function 'std::__1::priority_queue<int, std::__1::vector<int, std::__1::allocator<int> >,
(lambda at avg5.cpp:13:24)>::priority_queue' requested here
second(_VSTD::forward<_Args2>(_VSTD::get<_I2>(__second_args))...)
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/utility:507:11: note: in instantiation of function template specialization 'std::__1::pair<const int, std::__1::priority_queue<int,
std::__1::vector<int, std::__1::allocator<int> >, (lambda at avg5.cpp:13:24)> >::pair<const int &, 0>' requested here
: pair(__pc, __first_args, __second_args,
^
How to define and populate map of priority queues with custom comparison using lambda ?
Upvotes: 2
Views: 399
Reputation: 50308
You should not manipulate the type of lambdas. You should use std::function
in your case. Here is what the standard say about lambda types:
The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression. [...]
Lambda-expressions are not allowed in unevaluated expressions, template arguments, alias declarations, typedef declarations, and anywhere in a function (or function template) declaration except the function body and the function's default arguments.
You can find more information about this here and here.
Upvotes: 1