优先队列(priority_queue)--自定义排序

A: 默认排序

1,priority_queue< int > a;     // 基础类型, 默认是大顶堆,自动排

2,priority_queue<int, vector< int >, greater< int > > c;     //基础类型,变小根堆

#include<bits/stdc++.h>
#define ll long long
#define PP pair<int,int>
using namespace std;

int main()
{
    priority_queue< int,vector<int>,greater<int> > q;
    q.push(1);
    q.push(5);
    q.push(3);

    while(!q.empty())
    {
        printf("%d\n",q.top());
        q.pop();
    }

    return 0;
}

B: 自定义排序

       方法一: 运算符重载

结构体内 重载运算符<

#include<bits/stdc++.h>
#define ll long long
using namespace std;

#define PP pair<int,int>

struct Node{

    int x,y,z;
    Node(int a,int b,int c)
    {
        x=a,y=b,z=c;
    }
    bool operator<(const Node &a) const   //*****  运算符重载 < ,内置
    {
        return a.z>z;  //按z值降序
    }
};

int main()
{
    priority_queue<Node> q;
    q.push(Node(1,2,3));
    q.push(Node(3,9,1));
    q.push(Node(2,3,4));
    while(!q.empty())
    {
        printf("%d %d %d\n",q.top().x,q.top().y,q.top().z);
        q.pop();
    }

    return 0;
}

       方法二: 重写仿函数

priority_queue< 类型,vector< 类型 >,cmp> q;

#include<bits/stdc++.h>
#define ll long long
using namespace std;

#define PP pair<int,int>

struct cmp{    
            //重写仿函数
   bool operator()(PP a,PP b)
   {
       return a.first>b.first;
   }

};

int main()
{
     priority_queue<PP,vector<PP>,cmp> q;

     q.push(make_pair(4,6));
     q.push(make_pair(9,4));
     q.push(make_pair(6,1));
     while(!q.empty())
     {
         printf("%d %d\n",q.top().first,q.top().second);
         q.pop();
     }

    return 0;
}

### 优先队列自定义排序实现 在 C++ 中,可以通过模板参数指定优先队列的行为。标准库中的 `priority_queue` 提供了一个默认的最大堆行为,即每次弹出当前最大值。如果需要改变这种行为,则可以提供第三个模板参数作为比较函数对象或 lambda 表达式来定制排序逻辑[^1]。 以下是通过自定义比较器实现从小到大排序的一个示例: ```cpp #include <queue> #include <vector> #include <functional> std::priority_queue<int, std::vector<int>, std::greater<int>> q; ``` 上述代码片段展示了如何创建一个最小堆形式的优先队列,其中 `std::greater<int>` 是用于反转默认顺序的标准比较器。 对于 Python 而言,虽然没有直接类似于 C++ 的 `priority_queue` 类型,但可以借助内置模块 `heapq` 来模拟优先队列的功能。Python 还允许更灵活的方式来自定义排序规则,比如利用元组或者重载类的方法[^2]。 下面是一个基于 `heapq` 和元组实现优先级控制的例子: ```python import heapq class Node: def __init__(self, value, priority): self.value = value self.priority = priority def __lt__(self, other): return self.priority < other.priority pq = [] heapq.heappush(pq, Node('task1', 3)) heapq.heappush(pq, Node('task2', 1)) smallest = heapq.heappop(pq).value print(smallest) # 输出 task2 因为其优先级较低 (数值较小) ``` 此段代码演示了当两个节点被推入堆中时,按照它们各自的优先级字段进行排列的过程。这里的关键在于重新定义小于运算符 (`__lt__`) ,使得能够依据特定属性来进行比较操作。 另外,在某些情况下可能不需要完全构建新的数据类型也可以完成简单的自定义排序需求。例如可以直接存储带有权重信息的数据结构并依靠这些额外的信息决定次序。 ### 总结 无论是采用C++还是Python语言开发应用程序,都可以找到合适的技术手段去满足关于优先队列的各种复杂业务场景下的个性化要求。理解每种工具背后的工作原理有助于开发者做出最佳实践决策。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值