您的位置:首页 > 编程语言 > C语言/C++

C++ priority_queue

2015-07-09 19:42 537 查看
priority queue在许多的特别场合还是很实用的,优先队列是依据堆(二叉树)实现的,效率是O(lgn),因为它带来的便利,人们可以少写很多的代码,所以学习它是有必要的。

很多时候我们会自己定义比较函数,因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系,所以如果用>在g++编译器中编译不过,在函数中operator旁边还是用<吧,或者使用()。使用”priority_queue<int,vector<int>,greater<int> >“类似的语句可以将大到小的默认顺序改成小到大(头文件是<functional>,我们也可以自己写一个比较类设定优先级。

struct cmp{

bool operator()(type a,type b){

return -------;

}

};



#include<queue>
#include<iostream>
#include<functional>
#include<cmath>
#include<cstdio>
using namespace std;
struct cmp{
    bool operator()(int a,int b){
        return a>b;  //想让其从小到大输出,return >
    }
};
struct point{
    int x,y;
    void show(){
        printf("(%d,%d)\n",x,y);
    }
};
struct cmp2{
    bool operator()(point a,point b){
        return (abs(a.x)+abs(a.y))<(abs(b.x)+abs(b.y));
    }
};
int main(){ //优先队列默认按照从大到小的顺序排列输出
    freopen("cout.txt","w",stdout);
    int a[5]={3,5,2,1,7};
	priority_queue<int> v;
    for( int i = 0; i < 5; i++ ) {
       v.push(a[i]);
    }
    cout<<"v.size:"<<v.size()<<endl;
    while( !v.empty() ) {
       cout << v.top() << endl;
       v.pop();
    }
    cout<<"v.size:"<<v.size()<<endl;
    priority_queue<int,vector<int>,greater<int> > v2;
    //priority_queue<int,vector<int>,less<int> > v; //less 降序 ,greater 升序 
    
    for( int i = 0; i < 5; i++ ) {
       v2.push(a[i]);
    }
    cout<<"v2 从小到大输出:\n";
    while( !v2.empty() ) {
       cout << v2.top() << endl;
       v2.pop();
    }
    priority_queue<int,vector<int>,cmp> v3;
    for( int i = 0; i < 5; i++ ) {
       v3.push(a[i]);
    }
    cout<<"自定义比较的V3输出:\n";
     while( !v3.empty() ) {
       cout << v3.top() << endl;
       v3.pop();
    }
    cout<<"点输出优先级:与原点的曼哈顿距离。\n";
    point p[5]={{0,9},{12,0},{3,4},{6,5},{3,7}};
    priority_queue<point,vector<point>,cmp2> que;
    //priority_queue<point> que; 复杂的类型需要写出专门的比较类(上面的cmp2)。
    for(int i=0;i<5;i++)que.push(p[i]);
     while( !que.empty() ) {
       point tmp=que.top();
       tmp.show();
       que.pop();
    }
    return 0;
}


相关的结果:

v.size:5

7

5

3

2

1

v.size:0

v2 从小到大输出:

1

2

3

5

7

自定义比较的V3输出:

1

2

3

5

7

点输出优先级:与原点的曼哈顿距离。

(12,0)

(6,5)

(3,7)

(0,9)

(3,4)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: