![](/img/trans.png)
[英]Why is using a std::multiset as a priority queue faster than using a std::priority_queue?
[英]Why my code using priority_queue cannot compile?
嘗試使用priority_queue。 代碼是:
struct HeapNode
{
int val;
int row;
int col;
HeapNode(int a, int b, int c) : val(a), row(b), col(c) {}
};
class MyComparator
{
public:
bool operator()(HeapNode &n1, HeapNode &n2)
{
return n1.val < n2.val;
}
};
void myfunction()
{
std::priority_queue<HeapNode, std::vector<HeapNode>, MyComparator> hp1; //LINE1
std::priority_queue<HeapNode, MyComparator> hp2; //LINE2
}
嘗試了兩種方式,如 LINE1 和 LINE2 所示。 兩條線都不能通過編譯。
std::priority_queue 在構造函數中接受 3 個參數:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
在您的情況下, LINE1看起來不錯,應該可以編譯。 錯誤信息是什么?
在LINE2 中,您嘗試使用容器“MyComparator”(不是容器!)創建自定義類型(HeapNode)的 std::priority_queue。
用於存儲元素的底層容器的類型。 容器必須滿足 SequenceContainer 的要求。 此外,它必須提供具有通常語義的以下函數:front()、push_back()、pop_back()。 標准容器 std::vector 和 std::deque 滿足這些要求。
http://en.cppreference.com/w/cpp/container/priority_queue
“MyComparator”不是容器,它不支持所需的方法。
我檢查了你的代碼,注釋掉了LINE2並編譯。 你包括 和 嗎? 你在某處有主要功能嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.