码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 优先级队列

时间:2020-01-17 22:40:55      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:style   using   ret   col   bool   最大值   queue   less   ++   

priority_queue<int> q;//默认优先级队列的定义。

在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct cmp{
    bool operator()(int &a,int &b){
        return a > b;    //最小值优先
    }
};

struct cmp1{
    bool operator()(int &a,int &b){
        return a < b;    //最大值优先
    }
};
int a[] = {2,5,3,6,7,1,9,6,4};
int main()
{
    priority_queue<int,vector<int>,cmp> q;
    priority_queue<int,vector<int>,cmp1> q1;    //自定义优先级
    priority_queue<int,vector<int>,greater<int> > q2;    //内定义优先级(最小值)
    priority_queue<int,vector<int>,less<int> > q3;    //(最大值)
    for(int i = 0;a[i];i++){
        q.push(a[i]);
        q1.push(a[i]);
        q2.push(a[i]);
        q3.push(a[i]);
    }
    cout<<q.size()<<endl;

    cout<<"最小值优先"<<endl;
    while(!q.empty())
    {
        cout<<q.top()<<" ";
        q.pop();
    }
    cout<<"\n";
    cout<<"最大值优先"<<endl;
    while(!q1.empty()){
        cout<<q1.top()<<" ";
        q1.pop();
    }
    cout<<"\n";
    
    cout<<"最小值优先"<<endl;
    while(!q2.empty()){
        cout<<q2.top()<<" ";
        q2.pop();
    }
    cout<<"\n";
    
    cout<<"最大值优先"<<endl;
    while(!q3.empty()){
        cout<<q3.top()<<" ";
        q3.pop();
    }
    cout<<"\n";
    return 0;
}

运行结果:

9
最小值优先
1 2 3 4 5 6 6 7 9
最大值优先
9 7 6 6 5 4 3 2 1
最小值优先
1 2 3 4 5 6 6 7 9
最大值优先
9 7 6 6 5 4 3 2 1
第二种自定义优先级:
struct number1{ 
    int x; 
    bool operator < (const number1 &a) const { 
        return x>a.x;//最小值优先 
    } 
}; 
number1 num1[]={14,10,56,7,83,22,36,91,3,47,72,0}; 
int main()
{
  priority_queue<number1>q; 
  for(i=0;num1[i].x;i++) 
        q.push(num1[i]); 
  while(!q.empty()){
     cout<<q.top()<<" ";
     q.pop(); 
  }
  cout<<"\n";
}

c++ 优先级队列

标签:style   using   ret   col   bool   最大值   queue   less   ++   

原文地址:https://www.cnblogs.com/caozewen/p/12207728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!