用于C++中比较函数的Lambda不起作用
此代码产生错误:
priority_queue<int, vector<int>, [](int a, int b)->bool{return a>b;}> q;
为什么?(我知道对于这样的事情,我可以只使用std::greater或默认排序,但我正在尝试学习如何创建自定义比较器)
产生了2个错误:
error: no matching function for call to object of type lambda error: template argument for template type parameter must be a type
回答
您需要指定类型,而不是指定 lambda 表达式本身作为模板参数。并且 lambda 应该被指定为构造函数参数。
例如
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