C++如何使用自定义比较器声明priority_queue数组
想法来自: 使用自定义比较器在 C++ 中声明priority_queue ,
我尝试使用 lambda 作为priority_queue 的比较器,但是当我尝试声明它的数组时,出现错误。
代码:
class Klass{public:int raw_hash;int name;};
bool PriorByRaw(Klass a, Klass b){return a.raw_hash > b.raw_hash;}
auto prior = [](Klass a, Klass b){return PriorByRaw(a, b);};
//here comes the error before "[10]": expected a ';'
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
问题是如何以这种方式声明priority_queue数组?或者还有其他解决办法吗? 因为有一天我可能需要一个优先级队列,它使用其他函数作为比较器(比如“PriorByName”),覆盖“Klass”的 less 函数看起来不太好。
我已经尝试过但没有成功:
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
priority_queue<Klass, vector<Klass>, decltype(prior)> (pq(prior))[10];
With the idea from:
declaring a priority_queue in c++ with a custom comparator ,
I tried to use lambda as comparator for the priority_queue, but when I tried to declare an array of it, error comes.
code:
class Klass{public:int raw_hash;int name;};
bool PriorByRaw(Klass a, Klass b){return a.raw_hash > b.raw_hash;}
auto prior = [](Klass a, Klass b){return PriorByRaw(a, b);};
//here comes the error before "[10]": expected a ';'
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
The question is how can I declared an array of priority_queue in this manner? Or is there any other solution?
As one day I may need a priority que which use other functions as comparator (say "PriorByName"), overriding the less function for the "Klass" looks not good.
I've tried but didn't work:
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
priority_queue<Klass, vector<Klass>, decltype(prior)> (pq(prior))[10];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作来实现您想要的:
几点评论:
我用
const&
而不是按值传递Klass
对象,因为这样更有效。您有什么理由按值传递它吗?主要问题是使用
operator()
将 lambda 替换为比较器类。使用 lambda 和 decltype(prior) 需要编译器构造 lambda 的新实例,这是不允许的。MSVC 使用 lambda 时出现以下错误:
“错误 C3497:无法构造 lambda 实例”
如果您想了解更多信息,可以查找
C3497
。You can do the following to achieve what you want:
Several comments:
I replaced passing the
Klass
objects byconst&
instead of by value, since this is more efficient. Is there any reason you passed it by value ?The main issue is to replace the lambda with a comparator class with
operator()
. Using the lambda anddecltype(prior)
requires the compiler to construct a new instance of a lambda which is not allowed.MSVC gives the following error for using the lambda:
"error C3497: you cannot construct an instance of a lambda"
You can look
C3497
up if you'd like to get more info.从 C++ 20 开始,不带捕获的 lambda 是默认可构造的,因此您可以删除尝试的构造函数调用并使数组如下所示:
Since C++ 20, lambdas without captures are default constructible, so you can just remove the attempted constructor call and make the array like so: