C++_STL_Containers_priority_queue

priority_queue:优先队列

​ 优先级队列是一种容器适配器,根据一些严格的弱排序标准,专门设计使其第一个元素始终是它包含的最大元素。

此上下文类似于堆,其中可以随时插入元素,并且只能检索最大堆元素(优先级队列中顶部的元素)。

注意事项:
  1. 优先队列每次取值只能取得排序后的最大堆元素(或自定义排序后的最大或最小元素
  2. push() 方法 实质上是先调用了 底层容器对象的 push_back() ,然后在所有元素范围上调用 push_heap 算法将其重新排序到其在堆中的位置
  3. pop() 方法实质上是先调用 pop_heap 算法来保持 队列 的堆属性,然后调用底层容器对象的成员函数 pop_back 来删除该元素

常用API 如下:

  • empty(): 判断容器内是否为空
  • size(): 获取容器大小
  • top(): 获取 堆顶 元素(注意是排序后的元素)
  • push() : 插入新元素,注意每次插入都会引发 新排序
  • pop() : 删除 堆顶 元素,删除的元素是具有最高值的元素,注意每次删除都会引发新排序

在这里插入图片描述

初始化及自定义排序优先队列

默认大顶堆:

#include <queue>
using namespace std;

priority_queue<int> first; 
// 默认 大顶堆,此时为空队列

int myints[] = {10,60,50,20};
priority_queue<int> second(myints,myints + 4);
// 大顶堆,将数组 迭代入 队列中

pair<> 大顶堆:

priority_queue<pair<int,int> > third;
pair<int,int> a(3,4);
pair<int,int> b(3,5);
pair<int,int> c(4,3);
third.push(c);
third.push(b);
third.push(a);
// 大顶堆,先按照 pair 的 first 元素降序,first 元素相等时,再按照 second 元素降序

小顶堆:

#include <queue>
#include <vector>
using namespace std;

priority_queue<int,vector<int>,greater<int>> q;
// 使用 仿函数 greate<> 创建一个 小顶堆

pair<> 小顶堆:

#include <queue>
#include <vector>
using namespace std;

priority_queue < pair < int, int > , vector < pair < int, int >> , greater < pair < int, int >>> p;
// 大=小顶堆,先按照 pair 的 first 元素升序,first 元素相等时,再按照 second 元素升序

相当于将 小顶堆的 int 换成 pair<int,int>

自定义堆:

  • 重写仿函数

    struct Node{
    	int x, y;
    	Node( int a= 0, int b= 0 ):
     		x(a), y(b) {}
    };
    
    struct cmp{
    	bool operator() ( Node a, Node b ){
            //默认是less函数
    		//返回true时,a的优先级低于b的优先级(a排在b的后面)
            if( a.x== b.x ) {
                return a.y> b.y
            }
    	    return a.x> b.x; 
        }
    };
    
    priority_queue<Node, vector<Node>, cmp> q;
    // 自定义堆,队列中的每一项元素为 Node 构造体
    
  • 运算符重载

    struct Node{
        int x, y;
        Node(int a = 0, int b= 0):x(a), y(b) {}
    };
     
    bool operator < (const Node& a, const Node& b ){
        if (a.x == b.x) 
    		return a.y > b.y;
        return a.x > b.x; 
    }
     
    priority_queue<Node> q; 
    // 自定义 小顶堆
    
发布了51 篇原创文章 · 获赞 27 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_39446719/article/details/90171915