[英]c++: priority_queue: lambda-expression in template-argument
I am trying to create a priority_queue
with each element as a 3D vector.我正在尝试使用每个元素作为 3D 矢量创建一个
priority_queue
。 The element whose third dimension has the largest value would become the priority element.第三维具有最大值的元素将成为优先级元素。
Here is my code:这是我的代码:
priority_queue< vector<int>, vector<vector<int>>, [](vector<int> &v1, vector<int> &v2){
return v1[2] > v2[2];
}> pq{};
but I got the following error:但我收到以下错误:
error: lambda-expression in template-argument
Any idea what I did wrong?知道我做错了什么吗? Thanks!
谢谢!
You cant have a lambda (which is an object) in a type template declaration (where a type is needed. Do instead:在类型模板声明(需要类型的地方)中不能有 lambda(它是一个对象)。改为:
auto lambda = [](vector<int> &v1, vector<int> &v2){
return v1[2] > v2[2];
};
priority_queue< vector<int>, vector<vector<int>>,decltype(lambda)> pq{lambda};
We also need to pass the lambda
since it is not default constructible.我们还需要传递
lambda
因为它不是默认可构造的。
Form C++20 on, we can do the following:在 C++20 上,我们可以执行以下操作:
priority_queue< vector<int>, vector<vector<int>>,decltype([](vector<int> &v1, vector<int> &v2){
return v1[2] > v2[2];
};
)> pq{};
Here there come two new featurs of lambdas into play.这里有两个 lambda 的新特性发挥作用。 First that you can take the type of it directly (formally: In C++17 you cannot have a lambda-expression in unevaluated context) and second that lambdas are default constructible.
首先,您可以直接获取它的类型(正式:在 C++17 中,您不能在未评估的上下文中使用 lambda 表达式),其次,lambda 是默认可构造的。 But right now, that is not yet possible.
但现在,这还不可能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.