c++ - c++:struct和decltype比较器的priority_queue
问题描述
class Solution {
struct tree{
int x;
int y;
int height;
};
public:
int cutOffTree(vector<vector<int>>& forest) {
auto lambda1 = [](tree &t1, tree &t2){return t1.height < t2.height;};
priority_queue<tree, vector<tree>, decltype(lambda1)> pq1;
return 0;
}
};
但得到了错误:
知道我做错了什么吗?谢谢!
解决方案
priority_queue
需要Compare
用于比较的类型的实例。
的默认构造函数priority_queue
尝试将实例构造为Compare()
. 由于Compare
这是一个闭包类型,它会失败,因为闭包类型不是默认可构造的。
您需要将实例提供给构造函数。它将保存它的副本以供以后使用:
priority_queue<tree, vector<tree>, decltype(lambda1)> pq1{lambda1};
就目前而言,在 C++20 中,对于没有捕获的 lambda,这将不再是必需的,例如此处,因为它们将成为默认可构造的。您可以使用编译器中的实验性 C++20 支持来尝试这一点,例如编译器的-std=c++2a
or/std:c++latest
标志。
从 C++17 开始,您还可以使用类模板参数推导来避免两次命名 lambda 和值类型:
priority_queue pq1{lambda1, vector<tree>};
推荐阅读
- javascript - 如何使用 jquery 通过其属性获取元素?
- android - 如何在 Android 中创建一个像 Viber(或类似 facebook meesenger 的东西)中的头部气泡?
- c# - 使用 Amazon.AspNetCore.Identity.Cognito 时有什么方法可以解决 ConfirmEmailAsync(TUser user, string token) NullReferenceException?
- python - 我怎样才能一次将所有变量返回到 to_html() ?
- xaml - 连接来自 Xamarin.Forms 的 XAML 绑定中的变量的字符串
- python - 使用 bs4 从 Bloomberg 提取数据时出现问题
- python - Python中的Re.sub(删除最后一个_)
- linux - 我可以同时将文件传输到不同的 Windows 和 linux 服务器吗?
- docker - 使用远程代理转发时 docker buildkit mount ssh
- c - 如何将撇号更改为单个单位而不是 3 个字节?(\342 \200 \231) 使用 C