C++ 優先順序隊列(priority_queue)

來源:互聯網
上載者:User
文章目錄
  • 核心介面
  • 運用執行個體
C++ 優先順序隊列(priority_queue)
  優先順序隊列顧名思義是根據元素的優先順序被讀取,介面和queues非常相近。程式員可以通過template參數指定一個排序準則。預設的排序準則是利用operator< 形成降序排列,那麼所謂“下一個元素”就是“數值最大的元素”。
如果同時存在若干個數值最大的元素,無法確知究竟哪一個會入選。
標頭檔:<queue>
在檔案 <queue> 中,class priority_queue 定義如下:
namespace std {
    template < class T ,
           class Container = vector<T> ,
           class Compare = less <typename Container::value_type> >
    class priority_queue ;
}
由於priority queue需要用到STL heap演算法,所以其內部容器必須支援隨機存取迭代器。例如你可以使用deque來容納元素:
std::priority_queue< float, std::deque<float> > pbuffer ;
核心介面
push() 將一個元素置於priority queue中
top()  返回priority queue中的“下一個元素”
pop() 從priority queue 中移除一個元素
注意:如果priority queue 內沒有元素,執行top()和pop()會導致未定義的行為,應該先採用size()或empty()來檢驗容器是否為空白。
運用執行個體
// 使用VS2008 和 code::blocks 10.05調試通過
#include <iostream>
#include <queue>
using namespace std ;

int main()
{
priority_queue<float> q;

// insert three elements into the priority queue
q.push (66.6);
q.push (22.2);
q.push (44.4);

// read and print two elements
cout << q.top () << ' ';
q.pop ();
cout << q.top () << endl;
q.pop ();

// insert three more elements
q.push (11.1);
q.push (55.5);
q.push (33.3);

// skip one element
q.pop ();

// pop and print remaining elements
while (!q.empty ()) {
cout << q.top () << ' ';
q.pop ();
}
cout << endl ;
}
參考資料 《C++標準程式庫》侯捷 孟岩譯
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.