C++:优先队列

#ifndef PRIORITY_QUEUE
#define PRIORITY_QUEUE

// 对结构体排序, 由小到大 重载大于号,置为小于号的功能
struct node
{
    int x,y;
    friend bool operator>( const node &a, const node &b)
    {
   
        return a.x<b.x;
    }

};
void default_sort();
void uporder();
void user_defined();
void PRIORITY_test();

#endif // PRIORITY_QUEUE


#include "priority_queue.h"
#include<iostream>
#include<queue>
using namespace std;

//1.默认排序,大顶堆 优先输出元素大的数
void default_sort()
{
cout<<"default_sort"<<endl;

priority_queue<int>q1;
int n  = 6;
for(int i = 0;i<n;i++)
{
q1.push(i+1);
}
while(!q1.empty())
{

    cout<<q1.top()<<endl;
    q1.pop();
}

}
//2.升序排列 优先输出小的元素
void uporder()
{
 cout<<"uporder"<<endl;
 //小顶堆
    priority_queue<int,vector<int>,greater<int> >q1;
    int n  = 6;
    for(int i = 0;i<n;i++)
    {
    q1.push(9-i);
    }
    while(!q1.empty())
    {
        cout<<q1.top()<<endl;
        q1.pop();
    }
}

//3.自定义顺序
void user_defined()
{
    cout<<"user_defined_up"<<endl;
    //从小到大
    struct cmp1
    {
        bool operator()(int x,int y)
        {
   
        return x>y;
        }
    };
    priority_queue<int,vector<int>,cmp1>q1;
    int n  = 6;
    for(int i = 0;i<n;i++)
    {
    q1.push(9-i);
    }
    while(!q1.empty())
    {
        cout<<q1.top()<<endl;
        q1.pop();
    }

	//从小到大
    cout<<"user_defined_suzhu"<<endl;
    struct cmp2
    {
        int tmp[100];
        bool operator()(const int x,const int y)
        {
            return tmp[x]>tmp[y]; //升序
        }

    };
    priority_queue<int,vector<int>,cmp2>q2;
    for(int i = 0;i<n;i++)
    {
    q2.push(9-i);
    }
    while(!q2.empty())
    {
        cout<<q2.top()<<endl;
        q2.pop();
    }


	//对结构体排序 按照小的优先或者大的优先
    cout<<"user_defined_struct"<<endl;

    priority_queue<node>q4;
    node a;
    for(int i = 0;i<n;i++)
    {
        a.x = 9-i;
        a.y = i+2;
        q4.push(a);
    }
    while(!q4.empty())
    {
        cout<<q4.top().x<<q4.top().y<<endl;
        q4.pop();
    }



}





void PRIORITY_test()
{
    default_sort();
    uporder();
    user_defined();
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael.Scofield

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值