对指针类型的priority_queue元素进行排序

Sorting of priority_queue elements that are pointer type

本文关键字:元素 排序 queue 指针 类型 priority      更新时间:2023-10-16

假设我们有一个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;

通过重写运算符<方法或提供排序函数,我们可以让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字段)

相关文章: