![](/img/trans.png)
[英]Why is std::priority_queue sorting its container's elements?
[英]Sorting of priority_queue elements that are pointer type
假設我們有一個priority_queue,其中包含一堆聲明如下的ListNode對象:
class ListNode {
int val;
ListNode *next;
public:
explicit ListNode(int v) : val(v), next(NULL) {}
inline bool operator<(const ListNode& rhs) const {
return val < rhs.val;
}
};
std::priority_queue<ListNode> pq;
通過重寫operator <方法或提供排序函子,我們可以使priority_queue以val的升序保留ListNode對象。
我的問題是,priority_queue是否持有指向ListNode類的指針,而我可以對指針進行排序,以便val的指針按升序排列。 我怎么做?
std::priority_queue<ListNode *> pq1;
謝謝!
如您所說, std::priority_queue
接受比較函子作為第三個模板參數,該函子必須用於執行比較。
只需編寫自己的引用,然后再對這些項目進行解引用即可:
template<typename T>
struct PtrLess
{
bool operator()(const T* left, const T* right)
{
return *left < *right;
}
};
std::priority_queue<ListNode *, std::vector< ListNode * >, PtrLess< ListNode > > pq1;
指向ListNode
的指針就像日常指針。 您不能在兩個指針之間重載運算符。
但是,出於priority_queue
的目的,您可以覆蓋比較運算符。 它會像這樣:
struct ListNodePtrLess {
bool operator()(const ListNode* a, const ListNode* b) {
return a->val < b->val;
}
};
typedef std::priority_queue<ListNode*, std::vector<ListNode*>, ListNodePtrLess> MyPriorityQueue;
(另:你需要做ListNodePtrLess
的朋友ListNode
,還是讓它訪問val
在一些不同的方式字段)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.