【问题标题】:Priority Queue With a Custom Comparator No Matching Constructor具有自定义比较器的优先级队列没有匹配的构造函数
【发布时间】:2021-07-25 10:41:04
【问题描述】:

我正在尝试使用自定义比较器创建优先级队列,但以下代码给了我一个编译错误:

    auto comparator = [](std::pair<std::vector<int>, File&> const &a, std::pair<std::vector<int>, File&> const &b) {
      return a.first.front() > b.first.front();  
};

     std::priority_queue<std::pair<std::vector<uint64_t>, File&>,
      std::vector<std::pair<std::vector<uint64_t>, File&>>,
      decltype(comparator)> pq;

这是我得到的错误:

在模板中:没有匹配的构造函数用于初始化 'std::priority_queue<:pair moderndbs::file>, std::vector<:pair moderndbs::file>>, (lambda at

【问题讨论】:

  • 您的比较器知道如何比较 std::pair&lt;std::vector&lt;int&gt;, File&amp;&gt; 类型的值,但您正试图使用​​它来比较不同类型的值 std::pair&lt;std::vector&lt;uint64_t&gt;, File&amp;&gt;
  • 这并不能解决问题。
  • 由于您只将comparator 的类型传递给优先级队列,而不是实例本身,因此队列必须默认构造一个。但是,在 C++20 之前,lambda 是不可默认构造的。您需要在启用 C++20 支持的情况下进行编译才能使其工作,或者将 comparator 传递给 pq 的构造函数,如 std::priority_queue&lt;...&gt; pq{comparator}

标签: c++ templates stl std priority-queue


【解决方案1】:

您的问题在uint64_tint 之间不匹配。假设这是平方:

您至少需要 C++20 才能编译显示的代码。在 C++20 之前,lambdas are not default-constructible,并且您尝试默认构造您的 std::priority_queue

您需要将比较器显式传递给构造函数。使用 gcc 10 测试,-std=c++17:

#include <queue>
#include <functional>
#include <vector>
#include <cstdint>

class File{};

void foo()
{
    auto comparator = [](std::pair<std::vector<int>,
                 File &> const &a,
                 std::pair<std::vector<int>,
                 File &> const &b) {
        return a.first.front() > b.first.front();
    };

    std::priority_queue<std::pair<std::vector<int>,
                      File &>,
                std::vector<std::pair<std::vector<int>,
                          File &>
                    >,
                decltype(comparator)> pq{comparator};
}

使用默认构造函数 pq 失败。 gcc 10 用-std=c++20 编译默认构造的pq

PS:考虑用std::reference_wrapper 替换File &amp;,除非你真的打算做std::pair 中的File &amp;真正做的事情。

【讨论】:

  • 谢谢你,山姆!它现在可以工作了:) File 是一个自定义文件类,你能简单地提一下 reference_wrapper 的作用吗?我以后只会阅读这些文件,在这种情况下我应该使用哪个:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多