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 }

    运行结果:

  • 相关阅读:
    C#-使用Tuple传递多个参数
    CentOS 常用命令
    C#-ToString格式化
    java面对对象(六)--内部类、匿名内部类
    JAVA面对对象(五)——接口
    JAVA面对对象(四)——抽象类
    JAVA面对对象(三)——Super、static、final关键字
    Mybatis缓存
    重启博客
    某大神的装修笔记
  • 原文地址:https://www.cnblogs.com/lxc1910/p/10225883.html
Copyright © 2011-2022 走看看