博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++中小项堆声明和使用
阅读量:4684 次
发布时间:2019-06-09

本文共 801 字,大约阅读时间需要 2 分钟。

c++默认是大顶堆,小顶堆有两种声明方法:

1、对于基本类型直接用

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

如果基本类型是pair:

在代码第一行写:

typedef pair<int, int> P;

 priority_queue<P, vector<P>, greater<P>>pq;

注:greater<int> 是个好东西,把一个vector v从大到小排序用的就是sort(v.begin(), v.end(), greater<int>());

2、对于自定义类型,则必须自己重载 operator< 或者自己写仿函数

#include <iostream>

#include <queue>

using namespace std;

struct Node{

    int x, y;
    Node( int a= 0, int b= 0 ):
        x(a), y(b) {}
};

struct cmp{

    bool operator() ( Node a, Node b ){
        if( a.x== b.x ) return a.y> b.y;
       
        return a.x> b.x; }
};

int main(){

    priority_queue<Node, vector<Node>, cmp> q;
   
    for( int i= 0; i< 10; ++i )
    q.push( Node( rand(), rand() ) );
   
    while( !q.empty() ){
        cout << q.top().x << ' ' << q.top().y << endl;
        q.pop();
    }
   
    getchar();
    return 0;
}

转载于:https://www.cnblogs.com/yanchengwang/p/6184514.html

你可能感兴趣的文章
SpringBoot常用属性配置
查看>>
linux sdcv命令
查看>>
BZOJ4836: [Lydsy1704月赛]二元运算【分治FFT】【卡常(没卡过)】
查看>>
MPU6050开发 -- 数据分析(转)
查看>>
springmvc入门详解
查看>>
用户名、密码等15个常用的js正则表达式
查看>>
对比多层字典是否相同函数
查看>>
你在哪编程?你的程序原料是什么?
查看>>
ehcache 简介
查看>>
java uuid 例子
查看>>
linux zip 压缩密码
查看>>
【SICP练习】26 练习1.32
查看>>
Centos下安装破解Jira7的操作记录
查看>>
Python AES_ECB_PKCS5加密代码
查看>>
SpringBoot--外部配置
查看>>
C#中的线程三 (结合ProgressBar学习Control.BeginInvoke)
查看>>
sqlserver工作日常使用sql--持续完善中
查看>>
文件I/O与标准I/O
查看>>
大数据学习之路(持续更新中...)
查看>>
项目开发总结报告(GB8567——88)
查看>>