C++ 之 优先队列 priority_queue
2016-04-20 15:09
585 查看
解释:严格上而言不算队列,因为队列遵循先进先出;优先队列则是按照规则进行出队
使用:
(一)直接定义:
样例一:
输出:5 4 3 2 1 ;
(二)使用特定函数排序;
第二个参数:容器函数;
第三个参数:比较函数;
样例二:
(三)自定义优先级;(和sort类似)
比较成员函数:(结构体)
输出:
优先级值
9 5
8 2
6 1
2 3
1 4
使用:
(一)直接定义:
priority_queue<int>q1;定义一个优先队列q1,队列则按照降序(从大到小出队);
样例一:
int a[5]={3,1,2,4,5}; priority_queue<int>q1; for(int i = 0 ; i<5;i++) q1.push(a[i]); for(int i = 0 ; i < 5;i++) { printf("%d ",q1.top()); q1.pop(); } printf("\n");</span></strong>
输出:5 4 3 2 1 ;
(二)使用特定函数排序;
priority_queue<int,vector<int>,greater<int> >q2;//*这里的>>一定要分开!greater是从小到大的排序函数;
第二个参数:容器函数;
第三个参数:比较函数;
样例二:
int a[5]={3,1,2,4,5}; priority_queue<int,vector<int>,greater<int> >q2; for(int i = 0 ; i < 5;i++) q2.push(a[i]); for(int i = 0 ; i <5;i++) { printf("%d ",q2.top()); q2.pop(); } printf("\n");输出:1 2 3 4 5 ;
(三)自定义优先级;(和sort类似)
比较成员函数:(结构体)
struct node { friend bool operator< (node n1, node n2) { return n1.p < n2.p; } int p; int val; }b[5]; //*这里面没有 > 符号, 只支持 <; </span></strong>定义方式:
priority_queue<node>q3;样例三:
#include<iostream> #include<functional> #include<queue> using namespace std; struct node { friend bool operator< (node n1, node n2) { return n1.priority < n2.priority; } int priority; int value; }; int main() { const int len = 5; int i; int a[len] = {3,5,9,6,2}; //示例3 priority_queue<node> qn; node b[len]; b[0].priority = 6; b[0].value = 1; b[1].priority = 9; b[1].value = 5; b[2].priority = 2; b[2].value = 3; b[3].priority = 8; b[3].value = 2; b[4].priority = 1; b[4].value = 4; for(i = 0; i < len; i++) qn.push(b[i]); cout<<"优先级"<<'\t'<<"值"<<endl; for(i = 0; i < len; i++) { cout<<qn.top().priority<<'\t'<<qn.top().value<<endl; qn.pop(); } return 0; }
输出:
优先级值
9 5
8 2
6 1
2 3
1 4
相关文章推荐
- c++编程总结
- 【C语言】函数默认实现和用户自定义实现编程方法 -- 【weak, strong alias】
- pcl c++ 文件后缀名批处理修改 ply->pcd 走过的坑及问题
- 深入解析C语言中函数指针的定义与使用
- C++STL库中string类的find()和findfirstof()函数比较
- C++中的左值和右值
- C语言03数组
- C语言中的函数指针基础学习教程
- C++自定义缓冲区streambuf
- 位运算在算法题中的使用(C++)
- 实例解析C++中类的成员函数指针
- Effective C++笔记(六):继承与面向对象设计
- c++文件操作std::ifstream std::string::find() 和 std::string::npos
- c++知识总结
- C++编程中的函数指针初步解析
- C语言02基础深入理解(二)
- C 数列计算问题
- C++中的c_str()函数用法
- Hypertable 简介 一个 C++ 的Bigtable开源实现
- C++ WINDOWS API 如何使用NMAKE和CL编译