优先队列的排序写法

1.普通方法:

priority_queue<int>qu;


对入队的元素默认按照从大到小排序。

2.自定义优先级:

struct cmp{
  bool operator()(int x,int y)
{
    return x>y;   //从小到大排序。即x小的优先级高。
}
};

priority_queue<int,vector<int>,cmp>qu;



3.对结构体进行重载操作符:

struct node {
   int x,y;
   friend bool operator < (node a, node b)
   {
       return a.x>b.x;    //x小的优先级高。
   }
};


也可以:

struct node{
int x,y;
};
bool operator(const node &a,const node &b)
{
return a.x>b.x;
};


priority_queue<node>qu;


  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,我们可以通过自定义比较函数来实现自定义优先队列排序。比较函数是一个返回布尔值的函数,用于确定元素的优先级。在优先队列中,元素按照默认的排序规则进行排序,即大根堆或小根堆。默认情况下,元素按照从大到小的顺序排列,也就是大根堆。如果要实现不同的排序规则,我们可以自定义比较函数来改变元素的排序顺序。 下面是一个示例代码,展示了如何在C++中自定义优先队列排序: ```cpp #include <iostream> #include <queue> using namespace std; // 自定义比较函数,实现从小到大排序规则 struct Compare { bool operator() (int a, int b) { return a > b; } }; void custom_priority_queue_sort() { int source_data = {3, 5, 8, 1, 10, 2, 9, 15, 13, 16}; priority_queue<int, vector<int>, Compare> q; // 使用自定义的比较函数 for (auto n : source_data) q.push(n); while (!q.empty()) { cout << q.top() << endl; q.pop(); } } int main() { custom_priority_queue_sort(); return 0; } ``` 在上述代码中,我们定义了一个名为`Compare`的结构体,其中重载了小括号运算符`()`。在自定义的比较函数中,我们将元素按照从小到大的顺序排列,即返回`a > b`。然后在创建优先队列时,我们通过指定自定义比较函数`Compare`来改变排序规则。 运行以上代码,输出结果为: ``` 1 2 3 5 8 9 10 13 15 16 ``` 以上代码演示了如何在C++中自定义优先队列排序规则。通过自定义比较函数,我们可以实现各种不同的排序方式来满足特定需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值