此代码产生错误:
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
关于c++ - c++ 中比较函数的 Lambda 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67578528/