具有自定义比较器的优先级队列没有匹配的构造函数

Priority Queue With a Custom Comparator No Matching Constructor

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

    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, std::vector>, (lambda at

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

您至少需要 C++20 才能编译显示的代码。在 C++20 之前,lambdas ,并且您试图默认构造您的 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

P.S.: 考虑将 File & 替换为 std::reference_wrapper,除非你真的打算做 std::pair 中的 File &真的做。