简体   繁体   English

指针类型的priority_queue元素的排序

[英]Sorting of priority_queue elements that are pointer type

Let's say we have a priority_queue that holds a bunch of ListNode objects declared as below: 假设我们有一个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;

By overriding operator< method or providing a sorting functor we can have the priority_queue hold the ListNode objects in val's ascending order. 通过重写operator <方法或提供排序函子,我们可以使priority_queue以val的升序保留ListNode对象。

My question is if the priority_queue holds the pointers to ListNode class instead can I have the pointers sorted so that the val's pointed are in ascending order. 我的问题是,priority_queue是否持有指向ListNode类的指针,而我可以对指针进行排序,以便val的指针按升序排列。 How do I do that? 我怎么做?

std::priority_queue<ListNode *> pq1;

Thanks! 谢谢!

As you said, std::priority_queue accepts as third template parameter a comparison functor that it has to use to perform the comparisons. 如您所说, std::priority_queue接受比较函子作为第三个模板参数,该函子必须用于执行比较。

Just write your own that dereferences the items before comparing them: 只需编写自己的引用,然后再对这些项目进行解引用即可:

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;

A pointer to ListNode is like an everyday pointer. 指向ListNode的指针就像日常指针。 You cannot overload an operator between two pointers. 您不能在两个指针之间重载运算符。

However, you can override the comparison operator for the purpose of the priority_queue . 但是,出于priority_queue的目的,您可以覆盖比较运算符。 It would go something like this: 它会像这样:

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;

(also: you will need to make ListNodePtrLess a friend of ListNode , or let it access the val field in some different way) (另:你需要做ListNodePtrLess的朋友ListNode ,还是让它访问val在一些不同的方式字段)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM