[英]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::pair<std::vector, moderndbs::File &>, std::vector<std::pair<std::vector, moderndbs:: 的匹配構造函數文件 &>>, (lambda at
您的問題在uint64_t
和int
之間存在不匹配。 假設這是平方:
您至少需要 C++20 才能編譯顯示的代碼。 在 C++20 之前,lambdas 不是 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 &
,除非你真的打算做std::pair
中的File &
真正要做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.