zoukankan      html  css  js  c++  java
  • c++ priority_queue

    1、默认为大顶堆

     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     priority_queue<int> p;
     8     int i;
     9     for (i = 0; i < 5; i++)
    10         p.push(i);
    11     for (i = 0; i < 5; i++)
    12     {
    13         cout << p.top() << " ";
    14         p.pop();
    15     }
    16     return 0;
    17 }

    运行结果:

    2、小顶堆

     1 int main()
     2 {
     3     priority_queue<int, vector<int>, greater<int>> p;
     4     //vs2013需要#include <functional>
     5     int i;
     6     for (i = 0; i < 5; i++)
     7         p.push(i);
     8     for (i = 0; i < 5; i++)
     9     {
    10         cout << p.top() << " ";
    11         p.pop();
    12     }
    13     return 0;
    14 }

    运行结果:

    3、自定义

     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 
     5 struct Node
     6 {
     7     int a, b;
     8     Node(int x, int y) : a(x), b(y) {}
     9 };
    10 
    11 struct cmp
    12 {
    13     bool operator() (Node *x, Node *y)
    14     {
    15         if (x->a != y->a) return x->a < y->a; //大顶堆
    16         return x->b < y->b;
    17     }
    18 };
    19 int main()
    20 {
    21 
    22     priority_queue<Node *, vector<Node *>, cmp> p;
    23     Node *n = new Node(1, 2); p.push(n);
    24     n = new Node(1, 3); p.push(n);
    25     n = new Node(2, 3); p.push(n);
    26     while (!p.empty())
    27     {
    28         n = p.top();
    29         p.pop();
    30         cout << n->a << " " << n->b << endl;
    31     }
    32     return 0;
    33 }

    运行结果:

  • 相关阅读:
    质因数分解
    P1939 【模板】矩阵加速(数列)
    UVALive
    Python操作MySQL:pymysql模块
    Mysql数据库基础
    Redis管道和发布订阅
    Redis常用操作
    Redis操作集合,有序集合
    Redis操作list
    Redis操作hash
  • 原文地址:https://www.cnblogs.com/lxc1910/p/10225883.html
Copyright © 2011-2022 走看看