priority_queue
来源:互联网 发布:太原黑马程序员 编辑:程序博客网 时间:2024/06/02 08:58
特性:最大值(或者二元谓词认为是最大值)的元素位于队首,只允许在队首进行操作。迭代器类型为:随机访问迭代器。默认底层容器为:vector,可以使用deque,具体函数如下:
1. 构造器:
示例程序:
// constructing priority queues
#include <iostream> // std::cout
#include <queue> // std::priority_queue
#include <vector> // std::vector
#include <functional> // std::greater
class mycomparison
{
bool reverse;
public:
mycomparison(const bool& revparam=false)
{
reverse=revparam;
}
bool operator() (const int& lhs, const int&rhs) const
{
if (reverse) return (lhs>rhs);
else return (lhs<rhs);
}
};
int main ()
{
int myints[]= {10,60,50,20};
std::priority_queue<int> first;
std::priority_queue<int> second (myints,myints+4);
std::priority_queue<int, std::vector<int>,std::greater<int> >
third (myints,myints+4);
// using mycomparison:
typedefstd::priority_queue<int,std::vector<int>,mycomparison> mypq_type;
mypq_type fourth; // less-than comparison
mypq_type fifth (mycomparison(true)); // greater-than comparison
return 0;
}
解析:
The example does not produce any output,but it constructs different priority_queueobjects:
- First is empty.
- Second contains the four ints defined for myints, with 60 (the highest) atits top.
- Third has the same four ints, but because it uses greater instead of the default(which is less), it has 10 as itstop element.
- Fourth and fifth are very similar to first: they are both empty, except thatthese use mycomparison for comparisons, which is a special stateful comparisonfunction that behaves differently depending on a flag set on construction.
2. 判断优先队列是否为空:bool B=mypq.empty()
3. 返回优先队列中元素的个数:mypq.size();
4. 返回优先队列中最开头元素的引用:mypq.top()
5. 向优先队列中插入元素:mypq.push(elementvalue);
6. 删除优先队列最开头的元素:mypq.pop()
示例程序:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue <int> pq;
cout<<pq.empty()<<endl;
cout<<pq.size()<<endl;
for(int i=0;i<=5;i++)
{
pq.push(i);
}
cout<<pq.size()<<endl;
while(!pq.empty())
{
cout<<"The top element is:"<<pq.top()<<endl;
pq.pop();
}
return 0;
}
运行结果:
1
0
6
The top element is:5
The top element is:4
The top element is:3
The top element is:2
The top element is:1
The top element is:0
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- priority_queue
- Priority_queue
- priority_queue
- priority_queue
- priority_queue
- Iterator
- 百度地图SDK-----百度地图在线建议查询,结合AutoCompleteTextView实现搜索下拉列表。
- 测试程序运行时间
- Linux IPC实践(6) --System V消息队列(3)
- 全差分放大器简介
- priority_queue
- iOS面试题
- Runtime Error解析
- Time Limit Exceeded 解析
- 2014年总结
- Presentation Error解析
- OC点语法和变量作用域
- Compile Error解析
- string