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 -------;
}
};
相关的结果:
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)
很多时候我们会自己定义比较函数,因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系,所以如果用>在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)
相关文章推荐
- C++ HOJ 二阶魔方
- 探索C/C++大数快(自然数)模板
- Armadillo C++ linear algebra library 学习笔记(4)——矩阵的运算
- c++ 函数库查询
- C++ HOJ 猴子分桃
- C语言中关于哪些数据放在哪些区?
- C++构造函数
- Qt libstdc++-6.dll 报错
- c++filt看函数名
- C++用纯虚函数实现协议委托的例子
- Armadillo C++ linear algebra library 学习笔记(3)——矩阵的基本操作(2)
- Effective C++最新条款
- 图书馆管理系统(C++课程设计)
- VIM插件配置——ctags/taglist/omnicppcomplete/winmanager
- C/C++ 字符串与数字相互转换
- windows上判断磁盘是否为固态硬盘
- C++为QLabel增加单击事件
- C++默认构造函数
- 黑马程序员-c语言总结(结构体)
- c/c++ 函数指针和指针函数,变量指针和指针变量