STL容器_优先队列

来源:互联网 发布:淘宝怎么购买115会员 编辑:程序博客网 时间:2024/05/21 22:28

看详细注解:

#include<cstdio>#include<iostream>#include<vector>#include<queue>//采用头文件"functional"内定义优先级://piority_queue<int,vector<int>,greater<int>与less<int> >(s2,s3);#include<functional> using namespace std;typedef struct{    bool operator()(int &a,int &b){        return a>b;    //最小值优先 (若改为a<b即为 最大值优先)     }       //注a>b可理解为:假定a是一个最小值,优先输出比a还小的 ;ps:(与排序中sort函数相反) }cmp1;        //自定义数据结构struct number1{    int x;    bool operator < (const number1 &a) const {        return x>a.x;//最小值优先    }}; int a[]  = {1,6,3,7,8,54,0};  //测试案例 number1 num1[] = {14,10,56,7,83,0};int main(){priority_queue<int>s;                 //自定义(默认为最大值优先)     priority_queue<int,vector<int>,cmp1>s1;  //调用结构体最小值优先    priority_queue<int,vector<int>,greater<int> >s2; //最大值优先//注意“>>”会被认为错误,(相当于a>b)     priority_queue<int,vector<int>,less<int> >s3; //最大值优先(相当于a<b)     priority_queue<number1>que5; //最小优先级队列    for(int i = 0;a[i];i++){   s.push(a[i]);   s1.push(a[i]);   s2.push(a[i]);   s3.push(a[i]);   }      for(int j=0;num1[j].x;j++)        que5.push(num1[j]);      cout<<"自定义比较:"<<endl; while(!s.empty()) {cout<<s.top()<<" ";s.pop();}cout<<"\n"<<"调用结构体最小值优先:"<<endl;while(!s1.empty()) {cout<<s1.top()<<" ";s1.pop();}cout<<"\n"<<"调用greater<int>:"<<endl;while(!s2.empty()) {cout<<s2.top()<<" ";s2.pop();}cout<<"\n"<<"调用less<int>:"<<endl;while(!s3.empty()){cout<<s3.top()<<" ";s3.pop();}cout<<"\n"<<"调用最小优先级队列:"<<endl;while(!que5.empty()){//cout<<que5.top()<<" ";  //这里我也不知道为什么不能这么输出? printf("%d ",que5.top());   que5.pop();}return 0;}


原创粉丝点击