C++ priority_queue
template <class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
優先佇列預設採用vector實現,是最大堆。
Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.
This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue).
Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the “back” of the specific container, which is known as the top of the priority queue.
Member function
- empty : Test whether container is empty (public member function )
size Return size (public member function )
- top : Access top element (public member function )
- push : Insert element (public member function )
- emplace : Construct and insert element (public member function )
- pop : Remove top element (public member function )
- swap : Swap contents (public member function )
vector<int> nums{ 1, 9, 5, 7, 4 };
priority_queue<int> pq(nums.begin(), nums.end());// 9,7,5,4,1
cout << "top : " << pq.top() << endl;
pq.pop();// 7,5,4,1
cout << "after pop(), top : " << pq.top() << endl;
pq.push( 6 );// 7,6,5,4,1
pq.pop();// 6,5,4,1
cout << "after pop(), top : " << pq.top() << endl;
輸出:
top : 9
after pop(), top : 7
after pop(), top : 6
最小堆
vector<int> nums{ 1, 9, 7, 4 };
priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
//1, 4, 7, 9
cout << "top : " << pq.top() << endl;
pq.pop(); // 4, 7, 9
cout << "after pop(), top : " << pq.top() << endl;
pq.push( 5 ); // 4, 5, 7, 9
pq.pop(); // 5, 7, 9
cout << "after pop(), top : " << pq.top() << endl;
輸出:
top : 1
after pop(), top : 4
after pop(), top : 5
相關文章
- 【C++ STL】queue和priority_queueC++
- C++ STL 優先佇列 (priority_queue)C++佇列
- C++ priority_queue為例的比較函式C++函式
- STL(二十)priority_queue優先佇列容器佇列
- 例說資料結構&STL(七)——priority_queue資料結構
- uva 11997 priority_queue 應用舉例(超省時間!!!)
- C++::My Effective C++C++
- 【C++】C++之Lambda表示式C++
- 【C++】C++基礎知識C++
- C++C++
- 【C++】 C++知識點總結C++
- [C++之旅] 7 C++類和物件C++物件
- 【C++】C++之型別轉換C++型別
- [C++]C++程式設計例項C++程式設計
- C++ Primer!C++的“倚天劍”C++
- 【C++】C++的位元組對齊C++
- 學懂現代C++——《Effective Modern C++》之轉向現代C++C++
- 【C/C++】 C++暫存器優化C++優化
- C++學習筆記——C++ 繼承C++筆記繼承
- 【C++】 C++異常捕捉和處理C++
- C++效率(二)C++行內函數C++函數
- C++、C++學習之我見 (轉)C++
- c++:-3C++
- c++:-4C++
- c++:-5C++
- c++:-1C++
- c++:-2C++
- 求解c++C++
- C++——模板C++
- vector——C++C++
- C++概括C++
- 【C++】引用C++
- C++圖C++
- c++ binderC++
- c++ transformC++ORM
- c++ siteC++
- c++引用C++
- C++向量C++