zoukankan      html  css  js  c++  java
  • STL模板整理 priority_queue

    priority_queue

    优先队列是队列的一种,不过它可以按照自定义的一种方式(数据的优先级)来对队列中的数据进行动态的排序,每次的push和pop操作,队列都会动态的调整,以达到我们预期的方式来存储。

    定义:

    priority_queue<int> p;//最大值优先,是大顶堆一种简写方式
    priority_queue<int,vector<int>,greater<int>>q1;//最小值优先,小顶堆
    priority_queue<int,vector<int>,less<int> >q2;//最大值优先,大顶堆

    在使用时,我们会有很多时间用到根据结构体的某一个元素进行排序,下面给出定义结构体的优先级比较方式

    struct node
    {
        string name;
        int price;
        friend bool operator< (node a, node b)
        {
            return a.price < b.price; // 相当于less,这是大顶堆,反之则是小顶堆,最大值优先
        }
    } stu; //定义结构体变量
    
    这样直接可以:
    priority_queue<node > q;

    操作代码:

    #include <iostream>
    #include <queue>
    using namespace std;
    /*
    priority_queue<int> p;//最大值优先,是大顶堆一种简写方式
    priority_queue<int,vector<int>,greater<int>>q1;//最小值优先,小顶堆
    priority_queue<int,vector<int>,less<int> >q2;//最大值优先,大顶堆
    
    empty( )  //判断一个队列是否为空
    
    pop( )  //删除队顶元素
    
    push( )  //加入一个元素
    
    size( )  //返回优先队列中拥有的元素个数
    
    top( )  //返回优先队列的队顶元素
    
    优先队列的时间复杂度为O(logn),n为队列中元素的个数,其存取都需要时间。
    */
    /*
    struct node {
        string name;
        int price;
    } stu;
    struct cmp {
        bool operator () {
            return node.price < node.price; //相当于less, 大顶堆
        }
    }
    */
    struct node {
        string name;
        int price;
        friend bool operator< (node a, node b) {
            return a.price < b.price; // 相当于 less, 大顶堆,反之是小顶堆
        }
    } stu;
    
    int main() {
        priority_queue<int> p;//最大值优先,是大顶堆一种简写方式
        priority_queue<int,vector<int>,greater<int> > q1;//最小值优先,小顶堆
        priority_queue<int,vector<int>,less<int> > q2;//最大值优先,大顶堆
        priority_queue<node > q;  // 定义结构体变量
        int a[] = {5,4,3,2,1};
        for(int i = 0; i < 5; i++)
            p.push(a[i]);
        while(!p.empty()){
            cout << p.top() << " ";
            p.pop();
        }
        return 0;
    }
    宝剑锋从磨砺出 梅花香自苦寒来
  • 相关阅读:
    AcWing 1135. 新年好 图论 枚举
    uva 10196 将军 模拟
    LeetCode 120. 三角形最小路径和 dp
    LeetCode 350. 两个数组的交集 II 哈希
    LeetCode 174. 地下城游戏 dp
    LeetCode 面试题 16.11.. 跳水板 模拟
    LeetCode 112. 路径总和 递归 树的遍历
    AcWing 1129. 热浪 spfa
    Thymeleaf Javascript 取值
    Thymeleaf Javascript 取值
  • 原文地址:https://www.cnblogs.com/GHzcx/p/8672294.html
Copyright © 2011-2022 走看看