首页 > 解决方案 > 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;
    }
};

但得到了错误:

在此处输入图像描述

知道我做错了什么吗?谢谢!

标签: c++lambdapriority-queuedecltype

解决方案


priority_queue需要Compare用于比较的类型的实例。

的默认构造函数priority_queue尝试将实例构造为Compare(). 由于Compare这是一个闭包类型,它会失败,因为闭包类型不是默认可构造的。

您需要将实例提供给构造函数。它将保存它的副本以供以后使用:

priority_queue<tree, vector<tree>, decltype(lambda1)> pq1{lambda1};

就目前而言,在 C++20 中,对于没有捕获的 lambda,这将不再是必需的,例如此处,因为它们将成为默认可构造的。您可以使用编译器中的实验性 C++20 支持来尝试这一点,例如编译器的-std=c++2aor/std:c++latest标志。


从 C++17 开始,您还可以使用类模板参数推导来避免两次命名 lambda 和值类型:

priority_queue pq1{lambda1, vector<tree>};

推荐阅读