zoukankan      html  css  js  c++  java
  • STL对我们说,准备好了priority给我们用♫

    大根堆 :

    priority_queue<int,vector<int>,less<int> >q;
    或者简略写成 priority_queue<int>q;

    小根堆:

    priority_queue<int,vector<int>,greater<int> >q;

    但是我们不满足,想要另辟蹊径♪

    如何将自己定义的结构体作为 priority_queue 中的元素?
     
    几种实现方法:
     
    1.是他是他就是他,我们的好朋友:重载运算符~
    //大根堆
    struct Node {
    int x;
    Node(int x = 0) : x(x) {}
    bool operator < (const Node &rhs) const {
    return x < rhs.x;
    }
    };
    priority_queue<Node, vector<Node>, less<Node> > q;
    
    //小根堆
    struct Node {
    int x;
    Node(int x = 0) : x(x) {}
    bool operator > (const Node &rhs) const {
    return x > rhs.x;
    }
    };
    priority_queue<Node, vector<Node>, greater<Node> > q;
     

    2.自己写比较类

    //小根堆
    struct Node {
    int x;
    Node(int x = 0) : x(x) {}
     };
    struct cmp {
    bool operator () (Node a, Node b) {  //可爱的括号运算符
    return a.x > b.x;
     }
    };
    priority_queue<Node, vector<Node>, cmp> q;
    满堂花醉三千客,一剑霜寒十四州
  • 相关阅读:
    如何封装一个Ajax函数
    了解Ajax及Ajax如何发送请求
    jQuery的animate动画方法及动画排队问题解决
    jQuery的几种显示隐藏方法
    冲鸭!电瓶车
    Qt中使用HTTPS
    空非空
    河西走廊
    “财富自由”者之殇
    说鞋
  • 原文地址:https://www.cnblogs.com/phemiku/p/11619828.html
Copyright © 2011-2022 走看看