对指针类型的priority_queue元素进行排序
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;
通过重写运算符<方法或提供排序函数,我们可以让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
字段)
相关文章:
- 查找两个排序向量中共有的元素
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 高级选择排序 - 在一次迭代中搜索两个元素
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 将一系列已排序的元素划分为相邻组
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何在保持它们连接到同一元素的同时对 2 个数组进行排序?
- 使用 pair 创建priority_queue,以便在第一个元素相等时"<"第一个元素的排序,对第二个元素">"排序
- 如何将元素排序到矩阵C++
- 如何保持按第二个元素排序的对的优先级队列?
- 如何从两个数组中生成一对向量,然后使用CUDA/Thrust按对的第一个元素排序
- 部分排序数组,最后n个元素排序
- 如何对一对向量按降序排序,并按第二个元素排序