赞
踩
目录
priority_queue的名字中虽然带着queue但是他的底层是一个堆,并且默认情况下是一个大堆。
1. 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
3. 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。
4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
empty():检测容器是否为空
size():返回容器中有效元素个数
front():返回容器中第一个元素的引用
push_back():在容器尾部插入元素
pop_back():删除容器尾部元素
5. 标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指定容器类,则使用vector。
6. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数make_heap、push_heap和pop_heap来自动完成此操作
函数声明 | 接口说明 | |
priority_queue()/priority_queue(first, last) | explicit priority_queue (const Compare& comp = Compare(), const Container& ctnr = Container()); | 构造一个空的优先级队列 |
empty( ) | bool empty() const; | 检测优先级队列是否为空,是返回true,否则返回false |
top( ) | const value_type& top() const; | 返回优先级队列中最大(最小元素),即堆顶元素 |
push(x) | void push (const value_type& val); | 在优先级队列中插入元素x |
pop() | void pop(); | 删除优先级队列中最大(最小)元素,即堆顶元素 |
非成员函数重载:
函数声明 | 构造 | 接口说明 |
swap | void swap (priority_queue<T,Container,Compare>& x,priority_queue<T,Container,Compare>& y) noexcept(noexcept(x.swap(y))); | 交换 x和y的内容 |
默认情况下priority是一个大堆。
- #include <vector>
- #include <queue>
- #include <functional> // greater算法的头文件
- void TestPriorityQueue()
- {
- // 默认情况下,创建的是大堆,其底层按照小于号比较
- vector<int> v{3,2,7,6,0,4,1,9,8,5};
- priority_queue<int> q1;
- for (auto& e : v)
- q1.push(e);
- cout << q1.top() << endl;
- // 如果要创建小堆,将第三个模板参数换成greater比较方式
- priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
- cout << q2.top() << endl;
- }
如果在priority_queue中放自定义类型的数据,用户需要在自定义类型中提供> 或者< 的重载
- class Date
- {
- public:
- Date(int year = 1900, int month = 1, int day = 1)
- : _year(year)
- , _month(month)
- , _day(day)
- {}
- bool operator<(const Date& d)const
- {
- return (_year < d._year) ||
- (_year == d._year && _month < d._month) ||
- (_year == d._year && _month == d._month && _day < d._day);
- }
- bool operator>(const Date& d)const
- {
- return (_year > d._year) ||
- (_year == d._year && _month > d._month) ||
- (_year == d._year && _month == d._month && _day > d._day);
- }
- friend ostream& operator<<(ostream& _cout, const Date& d)
- {
- _cout << d._year << "-" << d._month << "-" << d._day;
- return _cout;
- }
- private:
- int _year;
- int _month;
- int _day;
- };
- void TestPriorityQueue()
- {
- // 大堆,需要用户在自定义类型中提供<的重载
- priority_queue<Date> q1;
- q1.push(Date(2018, 10, 29));
- q1.push(Date(2018, 10, 28));
- q1.push(Date(2018, 10, 30));
- cout << q1.top() << endl;
- // 如果要创建小堆,需要用户提供>的重载
- priority_queue<Date, vector<Date>, greater<Date>> q2;
- q2.push(Date(2018, 10, 29));
- q2.push(Date(2018, 10, 28));
- q2.push(Date(2018, 10, 30));
- cout << q2.top() << endl;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。