std::priority_queue
科技促进发展:优先事项[医]排队
Defined in header | | |
---|---|---|
template< class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type> > class priority_queue; | | |
优先级队列是一个容器适配器,默认为%29元素提供最大%28的恒定时间查找,而以对数插入和提取为代价。
用户提供的Compare可以提供以更改订单,例如使用std::greater<T>将导致最小元素显示为top()...
使用priority_queue
类似于管理堆在一些随机访问容器中,其好处是不能意外地使堆失效。
模板参数
T | - | The type of the stored elements. The behavior is undefined if T is not the same type as Container::value_type. (since C++17) |
---|---|---|
Container | - | The type of the underlying container to use to store the elements. The container must satisfy the requirements of SequenceContainer, and its iterators must satisfy the requirements of RandomAccessIterator. Additionally, it must provide the following functions with the usual semantics: front() push_back() pop_back() The standard containers std::vector and std::deque satisfy these requirements. |
Compare | - | A Compare type providing a strict weak ordering. |
front()
push_back()
pop_back()
标准容器std::vector
和std::deque
满足这些要求。
Compare - A [`Compare`](../concept/compare) type providing a strict weak ordering.
成员类型
Member type | Definition |
---|---|
container_type | Container |
value_compare (C++17) | Compare |
value_type | Container::value_type |
size_type | Container::size_type |
reference | Container::reference |
const_reference | Container::const_reference |
成员函数
(constructor) | constructs the priority_queue (public member function) |
---|---|
(destructor) | destructs the priority_queue (public member function) |
operator= | assigns values to the container adaptor (public member function) |
元素存取
顶层访问顶层元素%28公共成员函数%29
容量
空检查基础容器是否为空%28公共成员函数%29
Size返回元素数%28公共成员函数%29
修饰符
推送插入元素并对底层容器%28公共成员函数%29进行排序
嵌入%28C++11%29构造元素并对底层容器%28公共成员函数%29进行排序。
POP移除顶层元素%28公共成员函数%29
交换交换内容%28公共成员函数%29
成员对象
容器c底层容器%28受保护成员对象%29
比较比较函数对象%28受保护成员对象%29
非会员职能
std::swap(std::priority_queue) | specializes the std::swap algorithm (function template) |
---|
帮助者类
std::uses_allocator | specializes the std::uses_allocator type trait (function template) |
---|
例
二次
#include <functional>
#include <queue>
#include <vector>
#include <iostream>
template<typename T> void print_queue(T& q) {
while(!q.empty()) {
std::cout << q.top() << " ";
q.pop(
}
std::cout << '\n';
}
int main() {
std::priority_queue<int> q;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q.push(n
print_queue(q
std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q2.push(n
print_queue(q2
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1};
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp
for(int n : {1,8,5,6,3,4,0,9,7,2})
q3.push(n
print_queue(q3
}
二次
产出:
二次
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
8 9 6 7 4 5 2 3 0 1
二次
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。