【优先队列】STL之优先队列的使用方法
2014-03-07 21:11
711 查看
C++函数库中提供了以堆维持的优先队列。
这个队列就是一个最大 / 小堆。通过拿出堆顶来达到使用目的。
下面用几个示例来说明用法:
示例①——把一些数字从大到小输出。
示例②——把一些数字从小到大输出。
示例③——把一些结构体按其中某个元素从小到大输出。
运算符的重载:
struct node{
int x, y;
bool operator<(const node&a) const
{ if(a.x==x) return a.y<y; return a.x<x; } //根据x,y值比较node结构体的大小
};
这个队列就是一个最大 / 小堆。通过拿出堆顶来达到使用目的。
下面用几个示例来说明用法:
示例①——把一些数字从大到小输出。
#include <iostream> #include <cstring> #include <queue> #include <vector> using namespace std; priority_queue<int> xx; int main() { int n,num; while(cin>>n) { while(!xx.empty()) xx.pop(); while(n--) { cin>>num; xx.push(num); } while(!xx.empty()) { cout<<xx.top()<<" "; xx.pop(); } cout<<endl; } return 0; }
示例②——把一些数字从小到大输出。
#include <iostream> #include <cstring> #include <queue> #include <vector> using namespace std; struct cmp { bool operator ()(const int &i,const int &j) { return i>j; } }; priority_queue<int,vector<int>,cmp> xx; int main() { int n,num; while(cin>>n) { while(!xx.empty()) xx.pop(); while(n--) { cin>>num; xx.push(num); } while(!xx.empty()) { cout<<xx.top()<<" "; xx.pop(); } cout<<endl; } return 0; }
示例③——把一些结构体按其中某个元素从小到大输出。
#include <iostream> #include <cstring> #include <queue> #include <vector> using namespace std; struct Node { int x,y; }; struct cmp { bool operator ()(Node &a,Node &b) { return a.x>b.x; } }; priority_queue<Node,vector<Node>,cmp> xx; int main() { int n; Node node; while(cin>>n) { while(!xx.empty()) xx.pop(); while(n--) { cin>>node.x>>node.y; xx.push(node); } while(!xx.empty()) { Node temp=xx.top(); xx.pop(); cout<<temp.x<<" "<<temp.y<<endl; } } return 0; }
运算符的重载:
struct node{
int x, y;
bool operator<(const node&a) const
{ if(a.x==x) return a.y<y; return a.x<x; } //根据x,y值比较node结构体的大小
};
相关文章推荐
- STL 中优先队列的使用方法(priority_queu)
- STL 中优先队列的使用方法(priority_queu)
- STL 中优先队列的使用方法(priority_queu)
- STL优先队列的使用方法
- STL 中优先队列的使用方法(priority_queu)
- STL 中优先队列,队列以及statck的使用方法(priority_queu)
- STL中的优先队列priority_queue的使用方法
- stl中优先队列的使用方法
- STL中优先队列的使用方法
- STL 中优先队列的使用方法(priority_queue)
- STL 中优先队列的使用方法(priority_queu)
- c++STL中优先队列的使用
- STL优先队列使用
- STL中优先队列的使用
- UVa-136-Ugly Number STL 优先队列的基础使用
- 元素类型C++ 标准模板库STL 队列 queue 使用方法与应用介绍(一)
- STL中优先队列的使用
- STL优先队列的使用
- c++STL中优先队列的使用
- STL中栈和队列的使用方法