
优先队列
他和queue不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队
优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序
定义:priority_queue<数据类型, 容器类型, 比较的方式>
容器类型:必须是用数组实现的容器,比如vector--默认,deque等,但不能用list。STL里面默认用的是vector
比较的方式:数据的优先级
std::greater 升序队列 最小值优先队列
std::less 降序队列 最大值优先队列--默认
复制代码
#include<iostream>
#include <queue>
#include <vector>
int main() {
std::priority_queue <int, std::vector<int>, std::greater<int> > q; //创建优先队列对象
/*
参数3:std::greater 升序队列 最小值优先队列
std::less 降序队列 最大值优先队列
*/
int i=10;
q.push(i);
i = 9;
q.push(i);
i = 100;
q.push(i);
i = 6;
q.push(i);
i = 50;
q.push(i);
int n = q.size();
i = q.top(); //返回优先级最高元素,但不删除,( 在优先队列中,没有 front() 函数与 back() 函数 )
std::cout << i << std::endl;
std::cout << n << std::endl;
}
复制代码
复制代码
#include<iostream>
#include <utility>
#include <vector>
#include <queue>
int main()
{
//先按照pair的first元素降序;first元素相等时,再按照second元素降序:
std::priority_queue<std::pair<int, int> >p;
std::pair<int, int> a(3, 4);
std::pair<int, int> b(3, 5);
std::pair<int, int> c(4, 3);
p.push(a);
p.push(b);
p.push(c);
while (!p.empty())
{
std::cout << p.top().first << "\t" << p.top().second << std::endl;
p.pop();
}
return 0;
}
