随笔 - 108  文章 - 0  评论 - 11  阅读 - 11万

c++ 优先级队列(priority_queue)

从网上搜优先级队列用法,都是有些乱七八糟的,有几种用法都没说,直接贴代码。实在郁闷,于是自己在此归纳归纳。

废话不多说,直入主题。

优先级队列的核心是比较函数的实现。

比较函数有两种实现方法:

1、在结构体或类外面定义一个比较结构体。  //假如有个Point结构体。则new对象的时候:priority_queue<Point,vector<Point>,cmp> pg;其中cmp是自定义比较函数

2、在结构体或类中自己重载<操作符。   //假如有个Point结构体。这种方式定义优先级队列: priority_queue<Point> pg;

 

 

第1种方法实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
 
using namespace std;
 
class Point
{
public:
    int x,y;
};
 
struct cmp
{
    bool operator()(Point a,Point b)
    {
        return a.x>b.x;        //返回 !cmp
    }
};
 
priority_queue<Point,vector<Point>,cmp> pq;
Point p;
 
int main()
{
    int n;
    while(cin>>n)
    {
        while(!pq.empty()) pq.pop();
        while(n--)
        {
            cin>>p.x>>p.y;
            pq.push(p);
        }
        while(!pq.empty())
        {
            cout<<pq.top().x<<"-"<<pq.top().y<<" ";
            pq.pop();
        }
    }
    return 0;
}

  

第2种方法实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <queue>
#include <algorithm>
#include <functional>
#include <vector>
 
using namespace std;
 
class Point
{
public:
    friend bool operator <(Point a,Point b);
    int x,y;
};
 
//友元函数在外面实现 也可在类里面实现
bool operator <(Point a,Point b)      //优先级队列要求必须要实现<的重载,否则编译错误  而int型有默认的<函数。
{
    return a.x>b.x;         //返回比较结果的相反值,这种情况是从小到大排序
}
 
/** 友元函数在类里面实现如下
class Point
{
public:
    friend bool operator <(Point a,Point b)
    {
        return a.x>b.x;
    }
    int x,y;
};
**/
priority_queue<Point> pq;
Point p;
 
int main()
{
    int n;
    while(cin>>n)
    {
        while(!pq.empty()) pq.pop();
        while(n--)
        {
            cin>>p.x>>p.y;
            pq.push(p);
        }
        while(!pq.empty())
        {
            cout<<pq.top().x<<"-"<<pq.top().y<<" ";
            pq.pop();
        }
    }
    return 0;
}

  

posted on   北溟有鱼。  阅读(430)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示