標籤:containe ide rem 出隊 rank src width decltype 函數
priority_queue優先隊列/C++概述
priority_queue是一個擁有權值觀念的queue,只允許在底端加入元素,並從頂端取出元素。
priority_queue帶有權值觀念,權值最高者,排在最前面。
預設情況下priority_queue系利用一個max-heap完成,後者是一個以vector表現的complete binary tree。
定義
由於priority_queue完全以底部容器為根據,再加上heap處理規則,所以其實現非常簡單。預設情況下是以vector為底部容器。
priority_queue的所有元素,進出都有一定的規則,只有queue頂端的元素(權值最高者),才有機會被外界取用。priority_queue不提供遍曆功能,也不提供迭代器。
底部用到了:make_heap,push_heap,pop_heap(三個都是泛型演算法)
push_heap: 先利用底層容器的push_back()將新元素推入末尾,再重排heap。
pop_heap: 從heap內取出一個元素。它並不是真正將元素彈出,而是重排heap,然後再以底層容器的pop_back()取得被彈出的元素。
template< class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type>> class 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.
//底層只能是vector 和 deque 實現
- Compare - A Compare type providing a strict weak ordering.
std::greater
操作
| 常用函數 |
作用 |
| top |
取隊頭元素 |
| empty |
判斷優先隊列是否為空白 |
| size |
優先隊列中元素個數 |
| push |
向優先隊列中添加一個元素 |
| pop |
彈出隊頭元素(傳回值是void) |
example
#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); }
output:
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
http://www.frankyang.cn/2017/08/31/priorityqueue/
priority_queue優先隊列/C++